当意图向用户显示使用用户选择的区域格式格式化的字符串时,请使用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
: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);
我使这个示例比需要的更详细,但它有助于向您展示发生了什么。希望能帮助到你。
例子
浓缩下来,这看起来像:
//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");
例子