JS时间戳与日期格式的转换小结
作者:NCDS程序员
这篇文章主要介绍了JS时间戳与日期格式的转换小结,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
JS时间戳与日期格式的转换
1、将时间戳转换成日期格式:
function timestampToTime(timestamp) {
// 时间戳为10位需*1000,时间戳为13位不需乘1000
var date = new Date(timestamp * 1000);
var Y = date.getFullYear() + "-";
var M =
(date.getMonth() + 1 < 10
? "0" + (date.getMonth() + 1)
: date.getMonth() + 1) + "-";
var D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
var h = date.getHours() + ":";
var m = date.getMinutes() + ":";
var s = date.getSeconds();
return Y + M + D + h + m + s;
}
console.log(timestampToTime(1670145353)); //2022-12-04 17:15:532、将日期格式转换成时间戳:
var date = new Date("2022-12-04 17:15:53:555");
// 有三种方式获取
var time1 = date.getTime();
var time2 = date.valueOf();
var time3 = Date.parse(date);
console.log(time1); //1670145353555
console.log(time2); //1670145353555
console.log(time3); //1670145353000js基础之Date对象以及日期和时间戳的转换
js中使用Date对象来表示时间和日期:
获取年月日时分秒和星期等
var now = new Date(); now; now.getFullYear(); // 2021, 年份 now.getMonth(); // 2, 月份,月份范围是0~11,2表示3月 now.getDate(); // 4, 表示4号 now.getDay(); // 3, 星期三 now.getHours(); // 16, 表示19h now.getMinutes(); // 41, 分钟 now.getSeconds(); // 22, 秒 now.getMilliseconds(); // 473, 毫秒数 now.getTime(); // 1614847074473, 以number形式表示的时间戳
创建指定日期的时间对象
var d = new Date(2021, 3, 4, 16, 15, 30, 123);
将日期解析为时间戳
var d = Date.parse('2021-03-04 16:49:22.123');
d; // 1614847762123
// 尝试更多方式
(new Date()).valueOf();
new Date().getTime();
Number(new Date()); 时间戳转日期
var d = Date.parse('2021-03-04 16:49:22.123');
d; // 1614847762123
// 尝试更多方式
(new Date()).valueOf();
new Date().getTime();
Number(new Date()); 时间戳转自定义格式的日期
因为操作系统或者浏览器显示格式的不确定性,固定格式的日期只能自己拼接:
function getDate() {
var now = new Date(),
y = now.getFullYear(),
m = now.getMonth() + 1,
d = now.getDate();
return y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d) + " " + now.toTimeString().substr(0, 8);
}
getDate() // "2021-03-04 16:56:39"到此这篇关于JS时间戳与日期格式的转换的文章就介绍到这了,更多相关js时间戳与日期转换内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
