如何用javascript将日期时间格式化为字符串

How can I format a datetime into a string in javascript?

本文关键字:格式化 字符串 时间 日期 何用 javascript      更新时间:2023-09-26

当我试图用javascript将c#DateTime包含在我的网页中时,它显示为Date(1309513219184(。我希望它能显示为2011年1月7日09:30的样子。

有没有一种方法可以用javascript格式化它,或者我应该先做一些c#格式,然后作为javascript字符串打印?

如何格式化?

您可以这样做:

var d = new Date(milliseconds);
// var d = new Date(dateString);
// var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
d.toString();    // or d.toLocaleString()

或者您可以使用像datejs 这样的库

您可以使用javascript进行格式化。之前在StackOverflow中已经发布了同样的问题。

如何使用JavaScript中的格式规范将字符串转换为日期时间?

在将值发送到客户端之前,我会在C#代码中将DateTime变量更改为所需格式的字符串。你可以使用String.Format方法:

var newDateTime = Format.String("{MM/dd/yyyy hh:mm}", oldDateTime);

如何格式化Microsoft JSON日期?我们可以看到,您可以使用解析日期

var date = new Date(parseInt(jsonDate.substr(6)));

没有第二个参数的子字符串将从开始索引到结束,给出:

1309513219184)

哪个JavaScript可以成功解析为值为1309513219184的int。此值表示自1970年1月1日00:00:00 UTC以来的毫秒数。

至于格式,我个人更喜欢date.format.js。例如:

dateFormat(date, "mm/dd/yyyy hh:MM:ss")