我已经在微服务下写了将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 - 在没有任何npm的情况下将时间戳转换为MM DD,YYYY,反之亦然,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50020377/

10-12 15:45