JS日期时间戳/字符串格式相互转换

一、将字符串格式日期'YYYY-MM-DD'转为时间戳

var timeStamp = new Date('2021-11-30').getTime()
//1638230400000

二、将时间戳转换为字符串格式日期'YYYY-MM-DD'

var date = new Date(timeStamp);//Tue Nov 30 2021 08:00:00 GMT+0800
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
if (month < 10) {
    month = "0" + month;
}
if (day < 10) {
    day = "0" + day;
}
var result = year + "-" + month + "-" + day;//'2021-11-30'

你可能感兴趣的:(前端,javascript)