Created
December 24, 2019 02:20
-
-
Save cnjimbo/9b4bd08e63dd178ef790819be9de15d3 to your computer and use it in GitHub Desktop.
Javascript: overload method format of Date
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
let getPaddedComp = comp => parseInt(comp) < 10 ? '0' + comp : comp, | |
o = { | |
"[y|Y]{4}": date => date.getFullYear(), // year | |
"[y|Y]{2}": date => date.getFullYear().toString().slice(2), // year | |
"MM": date => getPaddedComp(date.getMonth() + 1), //month | |
"M": date => date.getMonth() + 1, //month | |
"[d|D]{2}": date => getPaddedComp(date.getDate()), //day | |
"[d|D]{1}": date => date.getDate(), //day | |
"h{2}": date => getPaddedComp( | |
(date.getHours() > 12) ? date.getHours() % 12 : date.getHours()), //hour | |
"h{1}": date => (date.getHours() > 12) ? date.getHours() % 12 : date.getHours(), //hour | |
"H{2}": date => getPaddedComp(date.getHours()), //hour | |
"H{1}": date => date.getHours(), //hour | |
"m{2}": date => getPaddedComp(date.getMinutes()), //minute | |
"m{1}": date => date.getMinutes(), //minute | |
"s+": date => getPaddedComp(date.getSeconds()), //second | |
"f+": date => getPaddedComp(date.getMilliseconds()), //millisecond, | |
"b+": date => (date.getHours() >= 12) ? 'PM' : 'AM' | |
}; | |
$.extend(Date.prototype, { | |
toString: function(format) { | |
let formattedDate = format; | |
for(var k in o) { | |
if(new RegExp("(" + k + ")").test(format)) { | |
formattedDate = formattedDate.replace(RegExp.$1, o[k](this)); | |
} | |
} | |
return formattedDate; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment