2017-04-23 282 views
1

我使用的NodeJS來從服務器的日期,但日期格式是yyyymmddThhmmss.SSSZ轉換yyyymmddThhmmss.SSSZ格式爲Unix TIMESTMP

20170423T203146.000Z 

我想這個日期字符串轉換成時代時間,以輕鬆計算此時間與當前時間之間的差異。 (時區將始終是UTC)

但是,我找不到解析此字符串的任何可能性,因爲庫似乎不接受這種日期字符串。

有人可以幫我解決這個問題嗎?

回答

1

Moment.js似乎給我糾正解析日期

var moment = require('moment') 

var date = moment("20170423T203146.052Z" , "YYYYMMDDThhmmss.SSS") 
console.log(date.format("YYYY MM DD hh mm ss SSS")) 

輸出:2017 04 23 08 31 46 052

+0

謝謝,那就是我搜索的內容。 將此轉換爲UNIX時間戳很容易 –

1

你應該看看Moment.js String+Format + Special Format

它似乎對你的時間串很好地工作已:

const moment = require("moment"); 

const werner = "20170423T203146.000Z"; 
console.log(moment.utc(werner).format()); 

const epochSec = moment.utc(werner).unix(); 
const epochMs = moment.utc(werner).valueOf(); 

console.log(epochSec, epochMs); 

Vi el Erfolg;)