2016-11-09 102 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)); 
 
});