Last active
June 6, 2023 01:34
-
-
Save polygonplanet/7952234 to your computer and use it in GitHub Desktop.
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 a date like YYYY-MM-DD. | |
* | |
* @param {string} template | |
* @param {Date=} [date] | |
* @return {string} | |
* @license MIT | |
*/ | |
function formatDate(template, date) { | |
var specs = 'YYYY:MM:DD:HH:mm:ss'.split(':'); | |
date = new Date(date || Date.now() - new Date().getTimezoneOffset() * 6e4); | |
return date.toISOString().split(/[-:.TZ]/).reduce(function(template, item, i) { | |
return template.split(specs[i]).join(item); | |
}, template); | |
} | |
console.log(formatDate('YYYY-MM-DD')); // 2015-02-18 | |
console.log(formatDate('MM/DD/YYYY, HH:mm:ss')); // 02/18/2015, 19:45:31 | |
console.log(formatDate('今ss秒')); // 今31秒 | |
var date = new Date('2015-02-01T01:23:45.678Z'); | |
console.log(formatDate('YYYY-MM-DD', date)); // 2015-02-01 | |
console.log(formatDate('MM/DD/YYYY, HH:mm:ss', date)); // 02/01/2015, 01:23:45 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is it possible to support the idea of displaying am or pm with this?