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

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


当前回答

试试这个:

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

其他回答

所以你需要在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

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

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

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

const theTime = new Date(1526813885836);
console.log(theTime.toString());
/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(太平洋标准时间)

下面是一个片段,使您能够将日期格式化为理想的输出:

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

var theyear = time.getFullYear();
var themonth = time.getMonth() + 1;
var thetoday = time.getDate();

document.write("The date is: ");
document.write(theyear + "/" + themonth + "/" + thetoday);