使用moment.js将my变量转换为12/12时间格式

Convert my my variable into a 12/12 time format using moment.js

本文关键字:时间 格式 转换 变量 moment js my 使用      更新时间:2023-09-26

我需要把我的时间从军事时间的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。但是当我把它代入力矩js时,它说它是一个invalid date

您没有使用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));
});