String::parseDate = ->
try
p = @.split ' '
t = [0,0,0]
d = p[0].split '-' if p.length > 0
t = p[1].split ':' if p.length > 1
new Date d[2], d[1]-1, d[0], t[0], t[1], t[2]
catch
false
String::isDate = ->
!!@.parseDate().valueOf()
String::isFactor = ->
!!new Date().parseFactor(@).valueOf()
String::fromNow = ->
(new Date).shift(@)
Date::parseFactor = (f) ->
mod = {
ms: 1
sec: 1e3
min: 6e4
mins: 6e4
hour: 36e5
hours: 36e5
day: 864e5
days: 864e5
week: 6048e5
weeks: 6048e5
}
+f.replace /([-+]{0,}\d+)\s(\w+)/g, (s, d, m) ->
+d * mod[m];
Date::shift = (f) ->
new Date @.getTime() + @.parseFactor(f)
Date::beginDay = ->
new Date(@.setHours 0,0,0,0)
Date::endDay = ->
new Date(@.setHours 23,59,59,999)
Date::nextDay = ->
@.shift('+1 day')
Date::prevDay = ->
@.shift('-1 day')
Date::format = (f) ->
zf = (n) ->
if n<10 then '0'+n else n
p = {
y: @.getFullYear()
M: zf @.getMonth()+1
d: zf @.getDate()
h: zf @.getHours()
m: zf @.getMinutes()
s: zf @.getSeconds()
}
f.replace /\%(\w+)/g, (s, k) ->
p[k] || s;
Date::mongoId = ->
ObjectId Math.floor(@/1e3).toString(16)+new Array(17).join '0' if ObjectId?
class DateRange
constructor: (@s, @f) ->
@s = @s.parseDate() if typeof @s == 'string'
@e = @s.shift @f
shift: (f) ->
@s = @s.shift f
@e = @e.shift f
@
prolong: (f) ->
@e = @e.shift f
@
range: () ->
@e - @s
inRange: (d) ->
d = d.parseDate() if typeof d == 'string'
@s < d < @e
isAfter: (d) ->
d = d.parseDate() if typeof d == 'string'
d < @s
isBefore: (d) ->
d = d.parseDate() if typeof d == 'string'
d > @e
toMongo: ->
{
$gte: @s
$lte: @e
}
console.log '14-02-1986 15:12:45'.isDate()
console.log 'Try to parse this!'.isDate()
console.log ''.isDate()
console.log '-13 days'.isFactor()
console.log '1c3 ddsfasays'.isFactor()
console.log ''.isFactor()
console.log '14-02-1986 15:12:45'.parseDate()
console.log '14-02-1986 15:12:45'.parseDate().shift '-10 days'
console.log '14-02-1986 15:12:45'.parseDate().shift('-10 days').beginDay()
console.log '14-02-1986 15:12:45'.parseDate().shift('-10 days').endDay()
console.log '14-02-1986 15:12:45'.parseDate().shift('-10 days').endDay().nextDay().prevDay()
console.log '14-02-1986 15:12:45'.parseDate().shift('-10 days').beginDay().endDay().nextDay().prevDay().shift('+10 days').format 'in %y year, day %d of %M time %h:%m:%s'
console.log '-90 days'.fromNow().mongoId()
dr = new DateRange '15-05-2015', '+5 days'
console.log dr.shift('35 min').prolong('1 day').prolong('321 sec').toMongo()
console.log dr.range()
console.log 'Yes!' if dr.inRange '17-05-2015'
console.log 'Yes!' if dr.isAfter '14-05-2015'
console.log 'Yes!' if dr.isBefore '22-05-2015'