JavaScript 将当前时间与时间戳转换为标准格式的方法

作者:资源驿站

时间:2026-10-30

浏览:602

本文介绍在 JavaScript 中将当前时间或指定时间戳转换为标准格式(YYYY-MM-DD HH:mm:ss)的几种实现方式。通过示例代码展示了如何手动拼接日期时间,以及利用 slice 方法处理单数字补零的技巧,帮助开发者快速实现时间格式化处理。

文章目录

JavaScript 将当前时间与时间戳转换为标准格式的方法

一、将当前系统时间转换为标准格式

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:07

JavaScript 时间戳转换为 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 ''
	}
}

至此,关于 JavaScript 时间转换标准格式及时间戳转换标准格式的示例代码介绍完毕。如需了解更多相关 JavaScript 时间戳转换内容,可搜索本站历史文章或继续浏览下方相关链接。感谢大家的支持!

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章