Skip to content

Instantly share code, notes, and snippets.

@polygonplanet
Last active June 6, 2023 01:34
Show Gist options
  • Save polygonplanet/7952234 to your computer and use it in GitHub Desktop.
Save polygonplanet/7952234 to your computer and use it in GitHub Desktop.

Revisions

  1. polygonplanet revised this gist Feb 18, 2015. 1 changed file with 10 additions and 5 deletions.
    15 changes: 10 additions & 5 deletions formatdate.js
    Original file line number Diff line number Diff line change
    @@ -2,17 +2,22 @@
    * Format a date like YYYY-MM-DD.
    *
    * @param {string} template
    * @param {Date=} [date]
    * @return {string}
    * @license MIT
    */
    function formatDate(template) {
    function formatDate(template, date) {
    var specs = 'YYYY:MM:DD:HH:mm:ss'.split(':');
    var date = new Date(Date.now() - new Date().getTimezoneOffset() * 60000);
    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')); // 2013-12-14
    console.log(formatDate('MM/DD/YYYY, HH:mm:ss')); // 12/14/2013, 06:53:24
    console.log(formatDate('今ss秒')); // 今24秒
    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
  2. polygonplanet created this gist Dec 13, 2013.
    18 changes: 18 additions & 0 deletions formatdate.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    /**
    * Format a date like YYYY-MM-DD.
    *
    * @param {string} template
    * @return {string}
    * @license MIT
    */
    function formatDate(template) {
    var specs = 'YYYY:MM:DD:HH:mm:ss'.split(':');
    var date = new Date(Date.now() - new Date().getTimezoneOffset() * 60000);
    return date.toISOString().split(/[-:.TZ]/).reduce(function(template, item, i) {
    return template.split(specs[i]).join(item);
    }, template);
    }

    console.log(formatDate('YYYY-MM-DD')); // 2013-12-14
    console.log(formatDate('MM/DD/YYYY, HH:mm:ss')); // 12/14/2013, 06:53:24
    console.log(formatDate('今ss秒')); // 今24秒