Skip to content

Instantly share code, notes, and snippets.

@countable
Last active December 23, 2015 07:39
Show Gist options
  • Save countable/6602149 to your computer and use it in GitHub Desktop.
Save countable/6602149 to your computer and use it in GitHub Desktop.
Fast and concise date formatting routine, using python style format strings.
zpad = (s='', n=0)->
s += ''
while s.length < n
s = '0' + s
s
#Javascript date formatting. Supports a subset of Python's formats for datetime.strptime
#http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
months = 'January,February,March,April,May,June,July,August,September,October,November,December'.split(',')
months_abbr = (m.substr(0,3) for m in months)
format_date = (d, format="%Y-%b-%d, %h:%i")->
map =
'%b': -> months_abbr[d.getMonth()]
'%B': -> months[d.getMonth()]
'%d': -> zpad d.getDate(), 2
'%e': -> d.getDate()
'%h': -> zpad d.getHours(), 2
'%i': -> zpad d.getMinutes(), 2
'%m': -> zpad d.getMonth(), 2
'%s': -> zpad d.getSeconds(), 2
'%Y': -> d.getFullYear()
'%y': -> zpad d.getYear(), 2
unless d instanceof Date
d = new Date d
format.replace /%./g, (match, offset, string)->
if map[match]
map[match]()
else
match
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment