如何通过JavaScript将Unix纪元转换为[年,月,日]

时间:2019-05-02 13:50:16

标签: javascript

我非常需要将存储在变量doc.creation_time中的时间戳转换为格式[year,month,day]

示例:

doc.creation_time = 1537492812 这应该转换为[2018,38,Fri]

有人可以帮忙

2 个答案:

答案 0 :(得分:2)

var creation_time = 1537492812;
var date = new Date(creation_time * 1000);
var weekday = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];

// UTC
console.log(date.getUTCFullYear(), date.getUTCMonth() + 1, weekday[date.getUTCDay()]);

// Local
console.log(date.getFullYear(), date.getMonth() + 1, weekday[date.getDay()]);

答案 1 :(得分:1)

您可以根据需要使用momentjs

var creation_time = 1537492812;
//var date = moment.unix(creation_time).format('YYYY,MM,ddd');
var date = moment.unix(creation_time).format('YYYY,w,ddd');
var result = date.split(',');
console.log(result);

var creation_time = 1537492812;
//var date = moment.unix(creation_time).format('YYYY,MM,w, ddd');
var date = moment.unix(creation_time).format('YYYY,w,ddd');
var result = date.split(',');
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>