Created
May 19, 2017 07:56
-
-
Save singhmohancs/0898eb61b8ca32a92115250a1d44c4c8 to your computer and use it in GitHub Desktop.
Date format + Javascript
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
/** | |
* Format datetime | |
* Usage: | |
* new Date().format('yyyy/MM/dd'), new Date().format('hh:mm:ss') | |
* @param {String} format | |
* @return {String} | |
*/ | |
Date.prototype.format = function(format) { | |
var self = this; | |
var half = false; | |
if (format && format[0] === '!') { | |
half = true; | |
format = format.substring(1); | |
} | |
if (format === undefined || format === null || format === '') | |
return self.getFullYear() + '-' + (self.getMonth() + 1).toString().padLeft(2, '0') + '-' + self.getDate().toString().padLeft(2, '0') + 'T' + self.getHours().toString().padLeft(2, '0') + ':' + self.getMinutes().toString().padLeft(2, '0') + ':' + self.getSeconds().toString().padLeft(2, '0') + '.' + self.getMilliseconds().toString().padLeft(3, '0') + 'Z'; | |
var h = self.getHours(); | |
if (half) { | |
if (h >= 12) | |
h -= 12; | |
} | |
return format.replace(regexpDATEFORMAT, function(key) { | |
switch (key) { | |
case 'yyyy': | |
return self.getFullYear(); | |
case 'yy': | |
return self.getYear(); | |
case 'MM': | |
return (self.getMonth() + 1).toString().padLeft(2, '0'); | |
case 'M': | |
return (self.getMonth() + 1); | |
case 'dd': | |
return self.getDate().toString().padLeft(2, '0'); | |
case 'd': | |
return self.getDate(); | |
case 'HH': | |
case 'hh': | |
return h.toString().padLeft(2, '0'); | |
case 'H': | |
case 'h': | |
return self.getHours(); | |
case 'mm': | |
return self.getMinutes().toString().padLeft(2, '0'); | |
case 'm': | |
return self.getMinutes(); | |
case 'ss': | |
return self.getSeconds().toString().padLeft(2, '0'); | |
case 's': | |
return self.getSeconds(); | |
case 'w': | |
case 'ww': | |
var tmp = new Date(+self); | |
tmp.setHours(0, 0, 0); | |
tmp.setDate(tmp.getDate() + 4 - (tmp.getDay() || 7)); | |
tmp = Math.ceil((((tmp - new Date(tmp.getFullYear(), 0, 1)) / 8.64e7) + 1) / 7); | |
if (key === 'ww') | |
return tmp.toString().padLeft(2, '0'); | |
return tmp; | |
case 'a': | |
var a = 'AM'; | |
if (self.getHours() >= 12) | |
a = 'PM'; | |
return a; | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment