2016-07-30 94 views
0

由於我幾乎完成了從FCC項目(https://www.freecodecamp.com/challenges/timestamp-microserviceMoment.js沒有返回正確的標準時間

我無法弄清楚爲什麼當輸入爲標準時間,也不會輸出它的Unix時間戳正確。

舉例來說,當我鍵入:

http://localhost:3000/January%201%201970 

它會輸出像這樣:

好像有8小時的偏移量(28800秒,但我申請即使在UTCOFFSET(),它不會改變。

var express = require('express'); 
 
var path = require('path') 
 
var app = express(); 
 
var moment = require('moment') 
 
var port = 3000; 
 
//homepage 
 
app.get('/', function(req, res) { 
 
    var fileName = path.join(__dirname, 'index.html'); 
 
    res.sendFile(fileName, function (err) { 
 
    if (err) {console.error(err)} 
 
    console.log('This is the homepage') 
 
    }); 
 
}); 
 

 
//input of the page 
 
app.get('/:dataString', function(req, res) { 
 
    var dataString = req.params.dataString; 
 
    var output; 
 
    //Using regex, checks if the dataString has only number characters 
 
    if(/^[0-9]*$/.test(dataString)){ 
 
    output = moment(dataString, "X") 
 
    } else{ 
 
    console.log(dataString) 
 
    output = moment(dataString, "MMMM DD YYYY") 
 
    console.log(output.utc().format("X")) 
 
    } 
 

 
    if (output.isValid()){ 
 
    res.json({ 
 
     unix: output.utc().format("X"), 
 
     natural: output.utc().format("MMMM D, YYYY") 
 
    }); 
 
    } else{ 
 
    res.json({ 
 
     unix: 'null', 
 
     natural: 'null' 
 
    }); 
 
    } 
 
}) 
 

 
app.listen(port,function(){ 
 
    console.log("turn on. Port is: ", port) 
 
})

回答

1

在您的代碼:

output = moment(dataString, "MMMM DD YYYY") 

這在當地時間創造了一會兒。由此產生的時間戳反映了您的本地時區與您的dataString時間點的UTC偏移量。

如果你想輸入的是基於UTC,那麼這將是:

output = moment.utc(dataString, "MMMM DD YYYY") 
+0

真棒!那就是訣竅 – Alejandro