Converting dates in YYYY-MM-DD to DD-MONTH in JavaScript

前端 未结 3 1039
清歌不尽
清歌不尽 2021-01-25 18:33

I have the following dates as strings..

2016-10-14
2016-10-15
2016-10-16
2016-10-17
2016-10-18
2016-10-19
2016-10-20

How can I dynamically conv

相关标签:
3条回答
  • 2021-01-25 19:06

    results=[]
    string=['2016-10-14', '2016-10-15', '2016-10-16', '2016-10-17', '2016-10-18', '2016-10-19', '2016-10-20']
    for(var i=0;i<string.length;++i){
      date=new Date(string[i]);
      list=date.toUTCString().split( " ")
    results.push(list[1]+" "+list[2])
    }
    
    
    console.log(results)

    0 讨论(0)
  • 2021-01-25 19:09
    var dates = ['2016-10-14', '2016-10-15', '2016-10-16', '2016-10-17', '2016-10-18', '2016-10-19', '2016-10-20'];
    
    function convertDates(str) {
      var d = new Date(str);
      var day = d.getDate();
      var month = d.toString().split(' ')[1];
      return day +' '+ month;
    }
    
    var final = [];
    
    dates.map(function(item) {
      final.push(convertDates(item)); 
    });
    

    That's it!

    0 讨论(0)
  • 2021-01-25 19:16

    There is no need for a Date object, and certainly you should not parse strings with the Date constructor.

    Note that:

    new Date('2016-10-14')
    

    will return a date for 13 October for users with a time zone west of Greenwich.

    Just reformat the string:

    /* Reformat a date like 2016-10-14 as dd MMM
    ** @param {string} s - date string to reformat
    ** @returns {string}
    */
    function formatDDMMM(s) {
      var months = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split(' ');
      var b = s.split(/\D/);
      return b[2] + ' ' + months[b[1]-1];
    }
    
    console.log(formatDDMMM('2016-10-14'));

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