Skip to content

Instantly share code, notes, and snippets.

@tcr
Created November 1, 2011 01:39
Show Gist options
  • Save tcr/1329614 to your computer and use it in GitHub Desktop.
Save tcr/1329614 to your computer and use it in GitHub Desktop.
Can you do Date formatting in JavaScript without a big library?
# tiny date formatter
# curly brackets used as a format specifier; can also zero-pad values
# aka (new Date).format("{FullYear}-{Month:2}-{Date:2}")
Date::format = (fmt) ->
fmt.replace /\{([^}:]+)(?::(\d+))?\}/g, (raw, comp, len) =>
unless (n = @["get"+comp]?())? then raw
else (Array(+len|0).join('0')+(n+(if comp == 'Month' then 1 else '')))[-len..]
Date::getFullMonth = ->
return 'January|February|March|April|May|June|July|August|September|October|November|December'.split('|')[@.getMonth()]
Date::getHoursMeridiem = -> ((@getHours()+11) % 12)+1
Date::getMeridiem = -> if @getHours() >= 12 then 'pm' else 'am'

A clever solution uses the built-in methods on the Date object in JavaScript, and writes a simple formatter that references these functions directly. By adding a few other value methods to the Date object, you can perform date formatting in just twenty lines of code.

["coffeescript","javascript","date","source","formatting","tiny"]
http://stackoverflow.com/questions/472644/javascript-collection-of-one-line-useful-functions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment