JavaScript时间格式化


title: JavaScript时间格式化
abbrlink: 26bcd43f
date: 2021-10-10 14:26:18
tags:
- Vue
categories:
- Vue技巧

JavaScript中时间格式化

有的时候,我们需要一定格式的 时间 比如2017-05-12 08:48 这样的格式。

时间格式化

第一种

function formatDate(time){
	var date = new Date(time);

	var year = date.getFullYear(),
		month = date.getMonth() + 1,//月份是从0开始的
		day = date.getDate(),
		hour = date.getHours(),
		min = date.getMinutes(),
		sec = date.getSeconds();
	var newTime = year + '-' +
				month + '-' +
				day + ' ' +
				hour + ':' +
				min + ':' +
				sec;
	return newTime;			
}

输出结果:

输出结果

前置 0

但是这里存在一个问题,就是,我想要的格式应该是 2017-05-12 08:49:25月、日、时、分、秒 小于10的时候,应该要前置一个0

改进代码:

第二种

function formatDate(time){
	var date = new Date(time);

	var year = date.getFullYear(),
		month = date.getMonth()+1,//月份是从0开始的
		day = date.getDate(),
		hour = date.getHours(),
		min = date.getMinutes(),
		sec = date.getSeconds();
	var newTime = year + '-' +
				(month < 10 ? '0' + month : month) + '-' +
				(day < 10 ? '0' + day : day) + ' ' +
				(hour < 10 ? '0' + hour : hour) + ':' +
				(min < 10 ? '0' + min : min) + ':' +
				(sec < 10 ? '0' + sec : sec);

	return newTime;			
}

formatDate(new Date().getTime());//2017-05-12 09:09:21

处理UTC格式时间

在前后端数据接口通信中,后台返回的时间往往是 UTC 格式的,即2020-10-12T10:31:35.891724+00:00这种,这可能是因为在数据库中存储时间格式选择的是 TIMESTAMP。

作为前端,我们需要将其转换为标准的本地格式,并用“YYYY-MM-DD HH:mm:ss”这种格式呈现给用户,用户才能看得懂。

转换

formatTime(time) {
      let date = new Date(time).toJSON()
      return new Date(+new Date(date) + 8 * 3600 * 1000)
        .toISOString()
        .replace(/T/g, ' ')
        .replace(/\.[\d]{3}Z/, '')
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值