gpt4 book ai didi

javascript - Chrome 的日期/时间格式问题

转载 作者:行者123 更新时间:2023-11-28 20:49:23 27 4
gpt4 key购买 nike

我得到如下 JSON 格式的日期/时间值:

"ChangedDate":"\/Date(1349469145000)\/"

在 FF 和 IE 中,我使用下面的辅助函数以 12 小时格式获取上述日期(10/5/2012 - 3:32:25 PM):

Handlebars.registerHelper('FormatDate', function (date) {
if (date == null)
return "";
else {
var value = new Date(parseInt(date.substr(6)));
return value.getMonth() + 1 + "/" + value.getDate() + "/" + value.getFullYear() + " - " + value.toLocaleTimeString();
}
});

但是,在 Chrome 中我仍然得到 24 小时格式 (10/5/2012 - 15:32:25)。

如何在 Chrome 中获取 12 小时格式的日期/时间值?

最佳答案

Use toLocaleTimeString when the intent is to display to the user a string formatted using the regional format chosen by the user. Be aware that this method, due to its nature, behaves differently depending on the operating system and on the user's settings.

您最好更改此行:

return value.getMonth() + 1 + "/" + value.getDate() + "/" + value.getFullYear() + " - " + value.toLocaleTimeString();

至:

return value.getMonth() + 1 + "/" + value.getDate() + "/" + value.getFullYear() + " - " + (value.getHours() > 12 ? value.getHours() - 12 : value.getHours()) + ":" + value.getMinutes() + ":" + value.getSeconds();

我们检查小时是否为 > 12,如果是,我们从该数字中减去 12。

(value.getHours() > 12 ? value.getHours() - 12 : value.getHours())

因此您的示例 15:32:25 将是 15 - 12 = 3: 3:32:25

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getSeconds

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getMinutes

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getHours

编辑

//set up example
var date = new Date("10/5/2012");
date.setHours(15,32,25,00);

//Get data from date
var month = date.getMonth()+1;
var day = date.getDate();
var year = date.getFullYear();

var hours = date.getHours();
var amOrPm = "AM";
if(date.getHours() > 12){
hours = date.getHours() - 12;
amOrPm = "PM";
}

var minutes = date.getMinutes();
if(minutes < 10)
minutes = "0" + minutes;

var seconds = date.getSeconds();
if(seconds < 10)
seconds = "0" + seconds;

var dateString = month + "/" + day + "/" + year + " - " + hours + ":" + minutes + ":" + seconds;

console.log(dateString);

我使这个示例比需要的更详细一些,但它有助于向您展示发生了什么。希望对您有所帮助。

<强> EXAMPLE

浓缩后看起来像这样:

//Get data from date
var dateString = (date.getMonth()+1) + "/" + date.getDate() + "/" + date.getFullYear() + " - " + (date.getHours() > 12 ? date.getHours() - 12 : date.getHours())+ ":" + (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) + ":" + (date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds()) + " " + (date.getHours() > 12 ? "PM" : "AM");

<强> EXAMPLE

关于javascript - Chrome 的日期/时间格式问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12784337/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com