Skip to content

Instantly share code, notes, and snippets.

@ironboy
Last active July 27, 2016 12:41
Show Gist options
  • Save ironboy/4e5f98721e2948ae917b to your computer and use it in GitHub Desktop.
Save ironboy/4e5f98721e2948ae917b to your computer and use it in GitHub Desktop.
date format
// Example usage niceFormat
// new Date().niceFormat('yyyy-mm-dd hh:ii:ss')
// Example usage countdown
// new Date().countdown(dateInFuture,'ii:ss')
// try with new Date().countdown(new Date(new Date().getTime()+3600000),"ii:ss")
(function(){
var a = {
yyyy: "getFullYear",
yy: "getFullYear",
mm: "getMonth",
dd: "getDate",
hh: "getHours",
ii: "getMinutes",
ss: "getSeconds"
};
Date.prototype.niceFormat = function(format){
var d = this;
var f = format;
var t;
for(var i in a){
t = 0;
t += i == "ii" && format.indexOf('hh') < 0 ? d[a['hh']]()*60 : 0;
t += i == "ss" && format.indexOf('ii') < 0 ?
d[a['hh']]()*3600 + d[a['ii']]()*60 : 0;
t += (d[a[i]]() + (i == "mm" ? 1 : 0));
t += '';
t = t.length < 2 ? "0" + t : t;
t = i == "yy" ? t.substring(t.length-2) : t;
f = f.split(i).join(t);
}
return f;
};
Date.prototype.countdown = function(date2,format){
// no dates just hh:ii:ss or ii:ss or ss
var diff = date2.getTime() - this.getTime();
var a = new Date("0000-01-01 00:00");
if(diff>0){
a = new Date(a.getTime()+diff);
}
var f = a.niceFormat(format);
return f;
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment