Chrome的日期/时间格式问题

我在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小时格式获取日期/时间值?

当意图是向用户显示使用用户选择的区域格式格式化的字符串时,请使用toLocaleTimeString 。 请注意,由于其性质,此方法的行为会有所不同,具体取决于操作系统和用户的设置。

你可能最好改变这条线:

 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 = 315 - 12 = 33:32:253: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); 

我让这个例子比需要的更详细,但它有助于向你展示正在发生的事情。 希望能帮助到你。

缩小它看起来像这样:

 //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");