我需要将军事时间 24 小时时间转换为常规 12/12 时间。
nextArrivalFinal2 = ((hour > 0 ? hour + ":" + (min < 10 ? "0" : "") : "") + min + ":" + (sec < 10 ? "0" : "") + sec);
console.log("nextArrival2", typeof nextArrivalFinal2)
console.log("nextArrival2", nextArrivalFinal2)
var convertedDate = moment(new Date(nextArrivalFinal2));
console.log('converted1', convertedDate)
console.log('converted', moment(convertedDate).format("hh:mm:ss"));
nextArrivalFinal2
将时间显示为 HH:MM:ss
格式的字符串。但是当我将其插入 moment js 时,它说这是一个无效日期
。
最佳答案
您没有使用 moment.js 解析时间,该行:
var convertedDate = moment(new Date(nextArrivalFinal2));
正在使用日期构造函数来解析像“13:33:12”这样的字符串,这可能会在每个实现中返回一个无效的日期(如果没有,它将返回一些可能与实际日期非常不同的内容)你期望的)。
使用 moment.js 解析字符串并告诉它格式,例如
var convertedDate = moment(nextArrivalFinal2, 'H:mm:ss'));
现在您可以获得的时间为:
convertedDate().format('h:mm:ss a');
但是,如果您想要的只是将 24 小时时间重新格式化为 12 小时时间,则只需要一个简单的函数:
// 13:33:12
/* Convert a time string in 24 hour format to
** 12 hour format
** @param {string} time - e.g. 13:33:12
** @returns {sgtring} same time in 12 hour format, e.g. 1:33:12pm
*/
function to12hour(time) {
var b = time.split(':');
return ((b[0]%12) || 12) + ':' + b[1] + ':' + b[2] + (b[0] > 12? 'pm' : 'am');
}
['13:33:12','02:15:21'].forEach(function(time) {
console.log(time + ' => ' + to12hour(time));
});
关于javascript - 使用 moment.js 将我的变量转换为 12/12 时间格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40500754/