Skip to content

Instantly share code, notes, and snippets.

@danielgreen
Created May 29, 2013 14:39
Show Gist options
  • Save danielgreen/5670778 to your computer and use it in GitHub Desktop.
Save danielgreen/5670778 to your computer and use it in GitHub Desktop.
Formatting JavaScript dates. Unashamedly nicked from https://gist.github.com/atesgoral/1005948 via http://www.140byt.es/keywords/date. See the linked Gist for more documentation. Alternatively see www.datejs.com and momentjs.com
function formatDate (d,f){return f.replace(/{(.+?)(?::(.*?))?}/g,function(v,c,p){for(v=d["get"+c]()+/h/.test(c)+"";v.length<p;v=0+v);return v})}
// Formats the date as a string e.g. "24/08/2013 17:04"
var formattedDate = formatDate(parsedDate, "{Date:2}/{Month:2}/{FullYear} {Hours:2}:{Minutes:2}");
//Instead of using classical format specifiers like "YYYY", "MM", "HH", "mm" etc.
//this function uses the Date instance getters like getFullYear, getMonth, etc.
//with support for zero-padding.
//For example, instead of:
//"YYYY-MM-DD HH:mm:ss"
//you can use:
//"{FullYear}-{Month:2}-{Date:2} {Hours:2}:{Minutes:2}:{Seconds:2}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment