我在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 = 3
: 15 - 12 = 3
: 3:32:25
: 3:32:25
。
编辑
//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");
例
以上就是jQuery教程分享Chrome的日期/时间格式问题相关内容,想了解更多jQuery开发(异常处理)及jQuery教程关注计算机技术网(www.ctvol.com)!)。
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/jquerytutorial/547453.html