【问题标题】:How to convert date format in js?如何在js中转换日期格式?
【发布时间】:2017-05-08 11:58:06
【问题描述】:

我得到的日期格式为

Sat Jan 28 2017 05:30:00 GMT+0530 (IST)

我希望这个日期像

January 2017

谁能提供帮助。谢谢。

【问题讨论】:

标签: javascript jquery node.js date


【解决方案1】:

您可以在Date 对象上使用toLocaleString()

date = new Date();

newDate = date.toLocaleString('en-US', {year: 'numeric', month: 'long'});

console.log(newDate);

更多信息在这里:Date.prototype.toLocaleString()

【讨论】:

    【解决方案2】:

    试试这个:D

    function myFunction() {
        var month = new Array();
        month[0] = "January";
        month[1] = "February";
        month[2] = "March";
        month[3] = "April";
        month[4] = "May";
        month[5] = "June";
        month[6] = "July";
        month[7] = "August";
        month[8] = "September";
        month[9] = "October";
        month[10] = "November";
        month[11] = "December";
    
        var d = new Date();
        var month = month[d.getMonth()];
        var year = d.getFullYear();
        document.getElementById("demo").innerHTML = month+year;
    }
    <button onclick="myFunction()">Try it</button>
    
    <p id="demo"></p>

    【讨论】:

      【解决方案3】:

      var date = new Date('Sat Jan 28 2017 05:30:00 GMT+0530 (IST)');
      var months = ["January", "February", "March", "April", "May", "June","July", "August", "September", "October", "November", "December"
      ];
      console.log(months[date.getMonth()],date.getFullYear());

      【讨论】:

        【解决方案4】:

        考虑使用 moment.js 来格式化/解析日期。这将允许您将输入/输出格式存储在配置中,而不是硬编码解析器实现。 http://momentjs.com/docs/#/parsing/

        【讨论】:

          【解决方案5】:
          var arr = ["January","February","March","April","May","June","July","August","September","October","November","December"];
          
          var str=arr[d.getMonth()]+""+d.getFullYear();
          
          console.log(str);
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2015-11-19
            • 1970-01-01
            • 2021-10-29
            • 1970-01-01
            • 2021-07-08
            • 2013-06-16
            • 2012-02-13
            相关资源
            最近更新 更多