我想要一个表示当前日期和时间的数字,比如Unix时间戳。


当前回答

要分别获得时间、月、日、年,这将起作用

var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();

其他回答

var timestamp = Number(new Date()); // current time as number
var d = new Date();
console.log(d.valueOf()); 
function getTimeStamp() {
    var now = new Date();
    return ((now.getMonth() + 1) + '/' +
            (now.getDate()) + '/' +
             now.getFullYear() + " " +
             now.getHours() + ':' +
             ((now.getMinutes() < 10)
                 ? ("0" + now.getMinutes())
                 : (now.getMinutes())) + ':' +
             ((now.getSeconds() < 10)
                 ? ("0" + now.getSeconds())
                 : (now.getSeconds())));
}

这一个有一个解决方案:在js中将unixtime stamp转换为tim

var a = new Date(UNIX_timestamp*1000);
var hour = a.getUTCHours();
var min = a.getUTCMinutes();
var sec = a.getUTCSeconds();

如果想要一种在Node.js中生成时间戳的基本方法,这很好。

var time = process.hrtime();
var timestamp = Math.round( time[ 0 ] * 1e3 + time[ 1 ] / 1e6 );

我们的团队正在使用此方法在本地主机环境中破坏缓存。输出是/dist/css/global.css?v=245521377,其中245521377是hrtime()生成的时间戳。

希望这会有所帮助,上面的方法也可以工作,但我发现这是Node.js中最简单的方法。