js 关于日期的格式化

第一种:将时间戳转化为标准时间

方法一:
var date = new Date(时间戳); //获取一个时间对象
function format(fmt, date) {
				var o = {
					"M+": date.getMonth() + 1, //月份   
					"d+": date.getDate(), //日   
					"h+": date.getHours(), //小时   
					"m+": date.getMinutes(), //分   
					"s+": date.getSeconds(), //秒   
					"q+": Math.floor((date.getMonth() + 3) / 3), //季度   
					"S": date.getMilliseconds() //毫秒   
				};
				if (/(y+)/.test(fmt))
					fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
				for (var k in o)
					if (new RegExp("(" + k + ")").test(fmt))
						fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
				return fmt;
  调用函数把var times= new Date(时间戳)获取到的时间转化为标准时间
  调用方式
	console.log(format('yyyy-MM-dd hh:mm:ss', times))
	console.log(format('yyyy-MM-dd', times))
	console.log(format('yyyy/MM/dd', times))
	console.log(format('yyyy年MM月dd日', times))
方法二:
//  日期的格式化 code = new Date() var data = (new Date()).getTime() 获取时间戳 
 参数说明: code为时间戳, true表示显示年月日  false表示显示年月日很时间
export function formatTimes(code, boolean) {
  const time = new Date(code)
  const year = time.getFullYear()
  const month = time.getMonth() + 1
  const date = time.getDate()
  const hour = time.getHours() < 10 ? '0' + time.getHours() : time.getHours()
  const min = time.getMinutes() < 10 ? '0' + time.getMinutes() : time.getMinutes()
  const sec = time.getSeconds() < 10 ? '0' + time.getSeconds() : time.getSeconds()
  if (boolean) {
    return year + '-' + month + '-' + date + ''
  } else {
    return year + '-' + month + '-' + date + '.' + hour + ':' + min + ':' + sec
  }
}

第二种:将标准时间转化为时间戳
var nowData = new Date();
有三种方式可以将标准时间转化为时间戳
区别如下:
var time1 = nowData.getTime();
var time2 = nowData.valueOf();
var time3 = Date.parse(nowData);
前两种是精确到毫秒,后面一种精确到秒
//1532868592176
//1532868592176
//1532868592000

这次在项目开发的时候后台返给我的数据是精确到秒,但是没有返回后面的三个零,前端处理的时候要加上三个零

参考文章:https://segmentfault.com/a/1190000000481753

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值