我有点啰嗦,但我会尽量说清楚

I'm bored, so I'm working on a "shoutbox", and I'm a little confused over one thing. I want to get the time that a message is entered, and I want to make sure I'm getting the server time, or at least make sure I'm not getting the local time of the user. I know it doesn't matter, since this thing won't be used by anyone besides me, but I want to be thorough. I've looked around and tested a few things, and I think the only way to do this is to get the milliseconds since January 1, 1970 00:00:00 UTC, since that'd be the same for everyone.

我是这样做的:

var time = new Date();
var time = time.getTime();

这将返回像1294862756114这样的数字。

有没有办法将1294862756114转换为更可读的日期,如DD/MM/YYYY HH:MM:SS?

所以,基本上,我正在寻找JavaScript的等效PHP的date();函数。


当前回答

您可以简单地使用Datejs库,以便将日期转换为所需的格式。

我已经进行了几次测试,它是有效的。

下面是一个片段,说明了如何实现这一目标:

var d = new Date(1469433907836);

d.toLocaleString(); // expected output: "7/25/2016, 1:35:07 PM"

d.toLocaleDateString(); // expected output: "7/25/2016"

d.toDateString();  // expected output: "Mon Jul 25 2016"

d.toTimeString(); // expected output: "13:35:07 GMT+0530 (India Standard Time)"

d.toLocaleTimeString(); // expected output: "1:35:07 PM"

其他回答

试试这个:

var time = new Date().toJSON();
/Date(1383066000000)/

function convertDate(data) {
    var getdate = parseInt(data.replace("/Date(", "").replace(")/", ""));
    var ConvDate= new Date(getdate);
    return ConvDate.getDate() + "/" + ConvDate.getMonth() + "/" + ConvDate.getFullYear();
}

var time = new Date().getTime();//获取你的电话号码 var date = new日期(时间);//创建日期对象 console.log (date.toString ());//结果:2011年1月12日星期三12:42:46 GMT-0800(太平洋标准时间)

使用日期JS

new Date().toString('yyyy-MM-d-h-mm-ss');

试着使用下面的代码:

var milisegundos = parseInt(data.replace("/Date(", "").replace(")/", ""));
var newDate = new Date(milisegundos).toLocaleDateString("en-UE");

享受它!