Skip to content

Instantly share code, notes, and snippets.

@zhasm
Last active December 15, 2015 17:39
Show Gist options
  • Save zhasm/5298196 to your computer and use it in GitHub Desktop.
Save zhasm/5298196 to your computer and use it in GitHub Desktop.
date diff
#!/usr/bin/env coffee -bc $0
class DateDiff
constructor: (dateStr='') ->
try
[year, month, date, hour, min] = dateStr.match(///^(\d{4})
-(\d{2})
-(\d{2})
\s
(\d{2})
:(\d{2})
///)[1..5]
@year = parseInt year
@month = parseInt month
@date = parseInt date
@hour = parseInt hour
@min = parseInt min
catch error
d = new Date()
@year = d.getFullYear()
@month = d.getMonth() + 1
@date = d.getDate()
@hour = d.getHours()
@min = d.getMinutes()
@repr = new Date(@year, @month - 1, @date, @hour, @min)
sec : ->
t = new Date(@repr)
(parseInt t.getTime()) / 1000
diff : (b) ->
if @sec() > b.sec()
big = @
small = b
leading = '过期'
else
big = b
small = @
leading = ''
d = {year:0, month: 0, date: 0, hour: 0, min: 0}
if big.repr.getMinutes() >= small.min
d.min = big.repr.getMinutes() - small.min
else
d.min = big.repr.getMinutes() + 60 - small.min
big.repr.setHours(big.repr.getHours() - 1)
if big.repr.getHours() >= small.hour
d.hour = big.repr.getHours() - small.hour
else
d.hour = big.repr.getHours() + 24 - small.hour
big.repr.setDate(big.repr.getDate() - 1)
if big.repr.getDate() >= small.date
d.date = big.repr.getDate() - small.date
else
d.date = big.repr.getDate() - small.date
y = new Date(big.repr)
y.setMonth(y.getMonth() + 1)
y.setDate(0)
d.date += y.getDate()
big.repr.setMonth(big.repr.getMonth() - 1)
if big.repr.getMonth() + 1 >= small.month
d.month = big.repr.getMonth() + 1 - small.month
else
d.month = big.repr.getMonth() + 1 - small.month + 12
big.repr.setFullYear(big.repr.getFullYear() - 1)
if big.repr.getFullYear() > small.year
d.year = big.repr.getFullYear() - small.year
else
d.year = 0
ret = ''
unit_cn = year: '年', month: '个月', date:'天', hour: '小时', min:'分钟'
count = 0
for unit in ['year', 'month', 'date', 'hour', 'min']
if not d[unit]
d[unit] = '零'
else
d[unit] = d[unit] + unit_cn[unit]
count += 1
ret += d[unit]
if count == 2
break
ret = leading + ret.replace(/^零*|零*$/g, '').replace(/零零+/, '零') or '到期'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment