gpt4 book ai didi

javascript - Moment.js 返回 "December 31, 1969"

转载 作者:太空宇宙 更新时间:2023-11-04 03:30:31 25 4
gpt4 key购买 nike

本质上,我正在重新创建 FCC 的后端项目之一:https://timestamp-ms.herokuapp.com/

如果我输入以下内容,它看起来就像我当前的代码: http://localhost:3000/1

它返回如下:

{"unix":"1","natural":"December 31, 1969"} 

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{
output = moment(dataString, "MMMM D, YYYY")
}

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

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

我预计会返回 1970 年 1 月 1 日,但我不确定错误来自何处。

最佳答案

格林尼治标准时间 (GMT) 时区为“1970 年 1 月 1 日”。 Moment 很可能会按照您自己的时区来格式化日期,如果您位于 GMT 以西,则该日期将变为“1969 年 12 月 31 日”。

要格式化 UTC 时区的日期,您可以编写:

moment('1', 'X').utc().format('MMMM D, YYYY')

这将输出“1970 年 1 月 1 日”。

关于javascript - Moment.js 返回 "December 31, 1969",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38648380/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com