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

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


当前回答

/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 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

假设以毫秒为单位的日期为1526813885836,因此您可以使用以下示例代码访问日期作为字符串:

console.log(new Date(1526813885836).toString());

为了清晰起见,请参阅下面的代码:

const theTime = new Date(1526813885836);
console.log(theTime.toString());

您可以简单地使用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();

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