Format JavaScript date as yyyy-mm-dd

后端 未结 30 2675
再見小時候
再見小時候 2020-11-22 01:28

I have a date with the format Sun May 11,2014. How can I convert it to 2014-05-11 using JavaScript?

相关标签:
30条回答
  • 2020-11-22 02:05

    toISOString() assumes your date is local time and converts it to UTC. You will get an incorrect date string.

    The following method should return what you need.

    Date.prototype.yyyymmdd = function() {         
    
        var yyyy = this.getFullYear().toString();                                    
        var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based         
        var dd  = this.getDate().toString();             
    
        return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
    };
    

    Source: https://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/

    0 讨论(0)
  • 2020-11-22 02:05

    No library is needed

    Just pure JavaScript.

    The example below gets the last two months from today:

    var d = new Date()
    d.setMonth(d.getMonth() - 2);
    var dateString = new Date(d);
    console.log('Before Format', dateString, 'After format', dateString.toISOString().slice(0,10))

    0 讨论(0)
  • 2020-11-22 02:06

    Just leverage the built-in toISOString method that brings your date to the ISO 8601 format:

    yourDate.toISOString().split('T')[0]
    

    Where yourDate is your date object.

    Edit: @exbuddha wrote this to handle time zone in the comments:

    const offset = yourDate.getTimezoneOffset()
    yourDate = new Date(yourDate.getTime() - (offset*60*1000))
    return yourDate.toISOString().split('T')[0]
    
    0 讨论(0)
  • 2020-11-22 02:06

    Retrieve year, month, and day, and then put them together. Straight, simple, and accurate.

    function formatDate(date) {
        var year = date.getFullYear().toString();
        var month = (date.getMonth() + 101).toString().substring(1);
        var day = (date.getDate() + 100).toString().substring(1);
        return year + "-" + month + "-" + day;
    }
    
    //Usage example:
    alert(formatDate(new Date()));

    0 讨论(0)
  • 2020-11-22 02:06

    When ES2018 rolls around (works in chrome) you can simply regex it

    (new Date())
        .toISOString()
        .replace(
            /^(?<year>\d+)-(?<month>\d+)-(?<day>\d+)T.*$/,
            '$<year>-$<month>-$<day>'
        )
    

    2020-07-14

    Or if you'd like something pretty versatile with no libraries whatsoever

    (new Date())
        .toISOString()
        .match(
            /^(?<yyyy>\d\d(?<yy>\d\d))-(?<mm>0?(?<m>\d+))-(?<dd>0?(?<d>\d+))T(?<HH>0?(?<H>\d+)):(?<MM>0?(?<M>\d+)):(?<SSS>(?<SS>0?(?<S>\d+))\.\d+)(?<timezone>[A-Z][\dA-Z.-:]*)$/
        )
        .groups
    

    Which results in extracting the following

    {
        H: "8"
        HH: "08"
        M: "45"
        MM: "45"
        S: "42"
        SS: "42"
        SSS: "42.855"
        d: "14"
        dd: "14"
        m: "7"
        mm: "07"
        timezone: "Z"
        yy: "20"
        yyyy: "2020"
    }
    

    Which you can use like so with replace(..., '$<d>/$<m>/\'$<yy> @ $<H>:$<MM>') as at the top instead of .match(...).groups to get

    14/7/'20 @ 8:45
    
    0 讨论(0)
  • 2020-11-22 02:06

    Here is one way to do it:

    var date = Date.parse('Sun May 11,2014');
    
    function format(date) {
      date = new Date(date);
    
      var day = ('0' + date.getDate()).slice(-2);
      var month = ('0' + (date.getMonth() + 1)).slice(-2);
      var year = date.getFullYear();
    
      return year + '-' + month + '-' + day;
    }
    
    console.log(format(date));
    
    0 讨论(0)
提交回复
热议问题