Dec
08
2023
js日期和时间戳互相转换的方法
作者:
绝缘体.. 发布:
2023-12-08 11:52 分类:
未分类 阅读:
抢沙发
js时间戳转换为日期的方法。
/**
* 时间戳格式化为年月日时分秒格式
* @param unixtimestamp
* @param fromat
*/
function unixTimestampToDate(unixtimestamp, fromat = 'yyyy-MM-dd') {
let date = new Date(parseInt(unixtimestamp) * 1000);
return date.format(fromat);
}
Date.prototype.format = function (format) {
var date = {
"M+": this.getMonth() + 1,
"d+": this.getDate(),
"h+": this.getHours(),
"m+": this.getMinutes(),
"s+": this.getSeconds(),
"q+": Math.floor((this.getMonth() + 3) / 3),
"i+": this.getMilliseconds()
};
if (/(y+)/i.test(format)) {
format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
}
for (var k in date) {
if (new RegExp("(" + k + ")").test(format)) {
format = format.replace(RegExp.$1, RegExp.$1.length == 1
? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
}
}
return format;
}
使用方法:
unixTimestampToDate(1702184209, 'yyyy-MM-dd hh:ii:ss'); //输出:2023-12-10 13:00:14
js日期转换为时间戳的方法。
/**
* 日期转换为时间戳
* @param string
* @returns {number}
*/
function dateToUnixTimestamp(string) {
var f = string.split(' ', 2);
var d = (f[0] ? f[0] : '').split('-', 3);
var t = (f[1] ? f[1] : '').split(':', 3);
return (new Date(
parseInt(d[0], 10) || null,
(parseInt(d[1], 10) || 1) - 1,
parseInt(d[2], 10) || null,
parseInt(t[0], 10) || null,
parseInt(t[1], 10) || null,
parseInt(t[2], 10) || null
)).getTime() / 1000;
}
【上一篇】js将form表单元素包装成json对象(jquery获取表单的所有元素组成json数据)
【下一篇】javascript的字符串编码函数escape,encodeURI,encodeURIComponent比较与分析
【下一篇】javascript的字符串编码函数escape,encodeURI,encodeURIComponent比较与分析
微信扫一扫,打赏作者吧~