gpt4 book ai didi

javascript - 将时间戳转换为 MM DD,YYYY,反之亦然,无需任何 npm

转载 作者:行者123 更新时间:2023-12-03 02:01:09 25 4
gpt4 key购买 nike

我在下面编写了微服务,将 unix 时间戳转换为 Dec 01,2017 等格式,反之亦然,并部署在此处 timestamp

在没有第三方 NPM 的情况下,他们是否有更好的方法来做到这一点

var path = require('path');
var express = require('express');
var app = express();
var bodyparser = require('body-parser');


app.route('/:date')
.get(function(req, res) {
// res.sendFile(process.cwd() + '/views/index.html');
var unix = null,
naturaldate = null;
//console.log(parseInt(timestamp),timestamp)
let timestamp = req.params.date;
if (!isNaN(timestamp)) {
let parsetime = new Date(parseInt(timestamp))
console.log(parsetime);
if (parsetime == 'Invalid Date') {
console.log("got invalid date")
send_response(null, null, res);
}
let parsenaturaldate = parsetime.toDateString().split(" ").slice(1);
let year = parsenaturaldate.splice(2, 0, ',');
year = parsenaturaldate.splice(1, 0, ' ')
naturaldate = parsenaturaldate.join("")
console.log(naturaldate)
unix = parseInt(timestamp)
send_response(unix, naturaldate, res);
} else {
unix = Date.parse(timestamp);

if (!isNaN(unix))
naturaldate = timestamp
else
send_response(null, null, res);
send_response(unix, naturaldate, res);
}
})

function send_response(unix, naturaldate, res) {
console.log(unix, naturaldate)
res.json({
"unix": unix,
"natural": naturaldate
})
}

app.listen(8083 || process.env.PORT, () => {
console.log("server is listening")
})

最佳答案

以下代码片段应该大致满足您的要求。如果您需要更改月份的格式,只需编辑 monthNames 数组即可。

var date = new Date(2017,11,1);
var monthNames = [
"jan", "feb", "mar",
"apr", "may", "jun", "jul",
"aug", "sep", "oct",
"nov", "dec"
];

var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();

day = day < 10 ? "0" + day.toString() : day.toString();

var result = monthNames[monthIndex] + ' ' + day + ',' + year;
console.log(result);

要反转该过程,您需要将字符串拆分为多个部分,在数组中找到月份名称的索引,然后从这些部分创建一个新的Date

关于javascript - 将时间戳转换为 MM DD,YYYY,反之亦然,无需任何 npm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50020377/

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