How do I get a date in YYYY-MM-DD format?

前端 未结 10 801
一生所求
一生所求 2020-12-17 17:16

Normally if I wanted to get the date I could just do something like

var d = new Date(); console.log(d);

The problem with doing that, is when I

相关标签:
10条回答
  • 2020-12-17 17:48

    Just use the built-in .toISOString() method like so: toISOString().split('T')[0]. Simple, clean and all in a single line.

    var date = (new Date()).toISOString().split('T')[0];
    document.getElementById('date').innerHTML = date;
    <div id="date"></div>

    Please note that the timezone of the formatted string is UTC rather than local time.

    0 讨论(0)
  • 2020-12-17 17:49

    If you are trying to get the 'local-ISO' date string. Try the code below.

    function (date) {
        return new Date(+date - date.getTimezoneOffset() * 60 * 1000).toISOString().split(/[TZ]/).slice(0, 2).join(' ');
    }
    

    +date Get milliseconds from a date.

    Ref: Date.prototype.getTimezoneOffset Have fun with it :)

    0 讨论(0)
  • 2020-12-17 17:52

    The below code is a way of doing it. If you have a date, pass it to the convertDate() function and it will return a string in the YYYY-MM-DD format:

    var todaysDate = new Date();
    
    function convertDate(date) {
      var yyyy = date.getFullYear().toString();
      var mm = (date.getMonth()+1).toString();
      var dd  = date.getDate().toString();
    
      var mmChars = mm.split('');
      var ddChars = dd.split('');
    
      return yyyy + '-' + (mmChars[1]?mm:"0"+mmChars[0]) + '-' + (ddChars[1]?dd:"0"+ddChars[0]);
    }
    
    console.log(convertDate(todaysDate)); // Returns: 2015-08-25
    
    0 讨论(0)
  • 2020-12-17 17:56

    Yet another way:

    var today = new Date().getFullYear()+'-'+("0"+(new Date().getMonth()+1)).slice(-2)+'-'+("0"+new Date().getDate()).slice(-2)
    document.getElementById("today").innerHTML = today
    <div id="today">

    0 讨论(0)
  • 2020-12-17 17:57

    What you want to achieve can be accomplished with native JavaScript. The object Date has methods that generate exactly the output you wish.
    Here are code examples:

    var d = new Date();
    console.log(d);
    >>> Sun Jan 28 2018 08:28:04 GMT+0000 (GMT)
    console.log(d.toLocaleDateString());
    >>> 1/28/2018
    console.log(d.toLocaleString());
    >>> 1/28/2018, 8:28:04 AM
    

    There is really no need to reinvent the wheel.

    0 讨论(0)
  • 2020-12-17 17:58

    By using moment.js library, you can do it:

    var datetime = new Date("2015-09-17 15:00:00"); datetime = moment(datetime).format("YYYY-MM-DD");

    0 讨论(0)
提交回复
热议问题