使用moment.js将my变量转换为12/12时间格式
Convert my my variable into a 12/12 time format using moment.js
我需要把我的时间从军事时间的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));
});
相关文章:
- Json数据包含日期和时间格式
- 更改angularjs中的日期-时间格式
- 转换日期时间格式
- 在JavaScript中转换日期/时间格式
- 时间格式不适用于dateTimePicker
- 将时间格式更改为24小时格式
- 将某个时间格式转换为日期对象
- 自定义angularjs过滤器日期时间格式额外字符
- dygraph x轴中的时间格式
- 如何使用javascript在html中查找日期时间格式
- 日期时间格式增加了一个小时
- 如何将24小时的日期时间格式转换为12小时的格式
- angularjs中的自定义时间格式
- 时间戳日期&时间格式-应用程序脚本-设置日期和时间格式
- 如何使用moment.js将秒转换为时间格式(YYYY:MM:DD HH:MM:ss)
- 如何将 JSON.NET 日期时间格式转换为javascript日期和时间
- 从服务器获取并传递给浏览器以在 Javascript 中格式化的日期时间格式
- getHours() 时间格式为 2016-04-29T19:00:00
- 使用jQuery重写日期/时间格式
- 如何转换SalesForce Api提供的UTC日期格式,并使用Google Apps脚本将其转换为本地日期和时间格式