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.
Created
November 1, 2011 01:39
-
-
Save tcr/1329614 to your computer and use it in GitHub Desktop.
Can you do Date formatting in JavaScript without a big library?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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