2016-11-09 101 views
0

我需要将我的时间在军用时间24小时内转换为常规12/12时间。使用moment.js将我的变量转换为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

+1

如果使用moment.js,你为什么要使用日期CON结构解析字符串?使用moment.js解析(并告诉它的格式)。 24小时制的格式被军事以外的许多组织和个人使用。 ;-) – RobG

+2

'新日期(“11:22:33”)'无效。为了使日期有效,它应该包括日期,月份和年份。 – jagzviruz

回答

2

你不与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'); 

但是,如果你想要的是重新格式化12小时时间24小时的时间,你只需要一个简单的函数:

// 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)); 
 
});