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

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();函数。


当前回答

使用日期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");

享受它!

所以你需要在getTime()之后将var time传递给另一个新的Date() 以下是我的例子:

var time = new Date()
var time = time.getTime()
var newTime = new Date(time)
console.log(newTime)
//Wed Oct 20 2021 15:21:12 GMT+0530 (India Standard Time)

这里输出的是我的datetime标准格式,它将是国家格式

如果你想要另一种格式,那么你可以在var newTime上应用另一个日期函数 就像

var newTime = new Date(time).toDateString()
console.log(newTime)
//Wed Oct 20 2021

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 datetime = 1383066000000; // anything
var date = new Date(datetime);
var options = {
        year: 'numeric', month: 'numeric', day: 'numeric',
    };

var result = date.toLocaleDateString('en', options); // 10/29/2013

查看更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString