将系统日期转换为格式化日期

时间:2016-09-05 13:26:23

标签: javascript

我想将系统日期转换为可读日期格式。但是,当我将系统日期作为参数传递给日期构造函数时,我得到Invalid date响应。如何正确执行此操作以显示格式化日期,例如GMT + 2的dd-mm-yyyy

var date = message.date; // => 1466663308000
        var dateObject = new Date(date);
        console.log(dateObject);

控制台输出:

  

无效日期

2 个答案:

答案 0 :(得分:1)

您必须确保时间戳值是一个数字而不是字符串:

    var date = message.date; 
    var dateObject = new Date(+date); // note the +
    console.log(dateObject);

一旦您获得了有效日期,就会有很多关于格式化日期的other questions here

答案 1 :(得分:0)

我试过代码,这是绝对正确的。 我可以得到正确的日期

var d=new Date(1466663308000);
document.write(d);

但我尝试了另一种方式:

var x = "1466663308000";
var d=new Date(x);
document.write(d);

我收到了“无效日期”,因此我猜,message.date应为字符串,请尝试long(message.date)