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

前端 未结 10 855
一生所求
一生所求 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: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
    

提交回复
热议问题