JS时间转换标准格式、时间戳转换标准格式的示例代码
作者:ruantianqing
这篇文章主要介绍了JS时间转换标准格式、时间戳转换标准格式的示例代码,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
JS时间转换标准格式、时间戳转换标准格式
一、当前时间转换为标准格式:
function getFormatDate() {
var date = new Date();
var month = date.getMonth() + 1;
var day = date.getDate();
var hour = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
month = (month<10)? '0'+ month : month;
day = (day<10)? '0'+ day : day;
hour = (hour<10)? '0'+ hour : hour;
minutes = (minutes<10)? '0'+ minutes : minutes;
seconds = (seconds<10)? '0'+ seconds : seconds;
var currentDate = date.getFullYear() + "-" + month + "-" + day
+ " " + hour + ":" + minutes + ":" + seconds;
return currentDate;
}
console.log(getFormatDate()) //2020-08-10 10:00:34二、时间戳转换为标准格式:
function formatDate(datetime) {
var date = new Date(datetime); //datetime时间戳为13位毫秒级别,如为10位需乘1000
var month = ("0" + (date.getMonth() + 1)).slice(-2), // getMonth是从1-11,所以需要加1
sdate = ("0" + date.getDate()).slice(-2), // -2表示从倒数第二个元素开始截取
hour = ("0" + date.getHours()).slice(-2),
minute = ("0" + date.getMinutes()).slice(-2),
second = ("0" + date.getSeconds()).slice(-2);
var thatDate = date.getFullYear() + "-" + month + "-" + sdate + " " + hour + ":" + minute + ":" + second;
// 返回
return thatDate;
}
console.log(formatDate(1599085447000)) //2020-09-03 06:24:07js时间戳转换2023-03-03 11:11:11格式方法
export function toTime(timestamp) {
//时间戳转换方法
if (timestamp ?? '' != '') {
const date = new Date(timestamp);
const formattedDate = date.getFullYear() + '-' + ('0' + (date.getMonth() + 1)).slice(-2) + '-' + ('0' + date
.getDate()).slice(-2); // 格式化日期
const formattedTime = ('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2) + ':' + (
'0' +
date.getSeconds()).slice(-2); // 格式化时间
return formattedDate + ' ' + formattedTime; // 拼接日期和时间
} else {
return ''
}
}到此这篇关于JS时间转换标准格式、时间戳转换标准格式的示例代码的文章就介绍到这了,更多相关js时间戳转换内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
