Skip to content

Instantly share code, notes, and snippets.

@nsfmc
Created January 9, 2011 13:34
Show Gist options
  • Save nsfmc/771684 to your computer and use it in GitHub Desktop.
Save nsfmc/771684 to your computer and use it in GitHub Desktop.
a strftime helper for js Date objects
/* Allows js Dates to return an object with formatted information
*
* The object has the same signature as php.net/date, so you can
* use that table to look up what the keys are.
* Most numbers are returned as strings so they can be 0 padded.
* not all keys are represented, but it's enough to save you time.
* no license, go nuts or whatever, or don't
* [email protected]
*/
Date.prototype.format = function(){
var months = ["January","February","March","April","May","June",
"July","August","September","October","November","December"];
var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday",
"Friday","Saturday","Sunday"];
return formats = {
// years, 4 and 2 digit verions
"Y":this.getFullYear()+"",
"y":(this.getFullYear()+"").slice(2,4),
// months: 3 letter abbrs, full month, 0 padded month number
"M":months[this.getMonth()].slice(0,3),
"F":months[this.getMonth()],
"n":(this.getMonth()+1) < 10 ? "0"+(this.getMonth()+1) : this.getMonth()+1,
// day of week: full length, abbreviated, & numerical
"l":days[this.getDay()],
"D":days[this.getDay()].slice(0,3),
"N":(this.getDay() == 0) ? 7 : this.getDay(),
// this requires a Date.prototype.getWeek function
// much like: https://gist.github.com/756300
"W":this.getWeek(),
// zero-padded date and non-padded
"d":this.getDate() < 10 ? "0"+this.getDate() : ""+this.getDate(),
"j":this.getDate()+"",
// 24 and 12 hour representations
"G":this.getHours()+"",
"g":(this.getHours() % 12 == 0) ? "12" : (this.getHours() % 12)+"",
// zero-padded 24 and 12 hour representations
"H":this.getHours() < 10 ? "0"+this.getHours() : ""+this.getHours(),
"h":(this.getHours() % 12) < 10 ?
((this.getHours() === 0) ? "12" : "0"+(this.getHours() % 12))
: ""+(this.getHours() % 12),
// AM/PM, & zero-padded minutes and seconds. milliseconds not padded
"A":(this.getHours() > 11) ? "PM" : "AM",
"a":(this.getHours() > 11) ? "pm" : "am",
"i":this.getMinutes() < 10 ? "0"+this.getMinutes() : ""+this.getMinutes(),
"s":this.getSeconds() < 10 ? "0"+this.getSeconds() : ""+this.getSeconds(),
"m":""+this.getMilliseconds(),
// fragile! timezone representation which depends on Date's tostring
// containing the timezone as (EST|DST|EDT|MST...)
"T":(/\((\w{3})\)/).exec(this+"") ? (/\((\w{3})\)/).exec(this+"")[1] : "",
"Z":this.getTimezoneOffset()
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment