Created
May 20, 2013 16:17
-
-
Save jkintscher/5613335 to your computer and use it in GitHub Desktop.
This file contains 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
token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g | |
timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[\-+]\d{4})?)\b/g | |
timezoneClip = /[^\-+\dA-Z]/g | |
i18n = | |
dayNames: [ | |
'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', | |
'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' | |
] | |
monthNames: [ | |
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', | |
'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' | |
] | |
pad = (val, len) -> | |
val = String(val) | |
len = len or 2 | |
val = '0' + val while (val.length < len) | |
val | |
this.dateFormat = (date, mask = 'ddd mmm dd yyyy HH:MM:ss') -> | |
# Passing date through Date applies Date.parse, if necessary | |
date = if date then new Date(date) else new Date() | |
throw SyntaxError('invalid date') if isNaN(date) | |
d = date.getDate() | |
D = date.getDay() | |
m = date.getMonth() | |
y = date.getFullYear() | |
H = date.getHours() | |
M = date.getMinutes() | |
s = date.getSeconds() | |
L = date.getMilliseconds() | |
o = date.getTimezoneOffset() | |
flags = | |
d: d | |
dd: pad(d) | |
ddd: i18n.dayNames[D] | |
dddd: i18n.dayNames[D + 7] | |
m: m + 1 | |
mm: pad(m + 1) | |
mmm: i18n.monthNames[m] | |
mmmm: i18n.monthNames[m + 12] | |
yy: String(y).slice(2) | |
yyyy: y | |
h: H % 12 or 12 | |
hh: pad(H % 12 or 12) | |
H: H | |
HH: pad(H) | |
M: M | |
MM: pad(M) | |
s: s | |
ss: pad(s) | |
l: pad(L, 3) | |
L: pad(if L > 99 then Math.round(L / 10) else L) | |
t: if H < 12 then 'a' else 'p' | |
tt: if H < 12 then 'am' else 'pm' | |
T: if H < 12 then 'A' else 'P' | |
TT: if H < 12 then 'AM' else 'PM' | |
Z: (String(date).match(timezone) or ['']).pop().replace(timezoneClip, '') | |
o: (o > 0 ? '-' : '+') + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4) | |
S: ['th', 'st', 'nd', 'rd'][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10] | |
mask.replace(token, ($0) -> | |
if $0 of flags then flags[$0] else $0.slice(1, $0.length - 1)) | |
Date.prototype.format = (mask) -> | |
return dateFormat(this, mask) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment