老程序员分享:JS日期格式转换

简介: 老程序员分享:JS日期格式转换

"

1.首先先把时间戳或带格式的日期转换成标准格式

如:2015-11-11,先用new Date('2015-11-11')转换成标准格式:Mon Nov 11 2015 08:00:00 GMT+0800 (中国标准时间)

如:1515260000000,先用new Date(1515260000000)转换成标准格式:Sat Sep 01 2018 08:00:00 GMT+0800 (中国标准时间)

将时间戳转换为指定的格式的方法:比如转换成 年月日时分秒 这种格式:yyyy-MM-dd hh:mm:ss 或者 yyyy-MM-dd。

?12345678910111213141516171819// 日期格式化1function parseTimeNew (date) { var ndate = new //代码效果参考:https://v.youku.com/v_show/id_XNjM5Nzg0Njc0MA==.html

Date(date) let type = 'yyyy-MM-dd' const o = { 'M+': ndate.getMonth() + 1, // 月份 'd+': ndate.getDate(), // 日 'h+': ndate.getHours(), // 小时 'm+': ndate.getMinutes(), // 分 's+': ndate.getSeconds(), // 秒 'q+': Math.floor((ndate.getMonth() + 3) / 3), // 季度 'S': ndate.getMilliseconds() // 毫秒 } if (/(y+)/.test(type)) type = type.replace(RegExp.$1, (ndate.getFullYear() + '').substr(4 - RegExp.$1.length)) for (const k in o) { if (new RegExp('(' + k + ')').test(type)) type = type.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o【k】) : (('00' + o【k】).substr(('' + o【k】).length))) } return type}

使用方法:

?1parseTimeNew (1842760000000)//将前面的时间戳的格式转换成yyyy-MM-dd样式

2.把日期转换成时间戳,获取精准的时间戳

?1new Date(time).getTime()

使用方法:

?1console.log(new Date('2013-11-11 13:34:04').getTime())

3.判断日期是否为昨天

?1234567// 判断日期是否为昨天function isYestday (theDate) { let date = (new Date())// 当前时间 let today = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() // 今天凌晨 //代码效果参考:https://v.youku.com/v_show/id_XNjQwMDEyMTg2OA==.html

let yestday = new Date(today - 24 3600 1000).getTime() return theDate.getTime() = theDate.getTime()

}

//调用

let time = new Date('2013-11-11')

isYestday(time) //false time为标准时间格式 Mon Nov 11 2013 08:00:00 GMT+0800 (中国标准时间)

4.js获取今天0点的时间戳和23.59分的时间戳

?12let startTime1 = new Date(new Date(new Date().toLocaleDateString()).getTime()); // 当天0点let endTime1 = new Date(new Date(new Date().toLocaleDateString()).getTime() +24 60 60 * 1000 -1);// 当天23:59


"
image.png
相关文章
|
2月前
|
存储 JavaScript 前端开发
写给不耐烦程序员的 JavaScript 指南(二)
写给不耐烦程序员的 JavaScript 指南(二)
60 0
|
2月前
|
存储 JavaScript 前端开发
写给不耐烦程序员的 JavaScript 指南(四)
写给不耐烦程序员的 JavaScript 指南(四)
34 0
|
2月前
|
JavaScript 前端开发 测试技术
写给不耐烦程序员的 JavaScript 指南(三)
写给不耐烦程序员的 JavaScript 指南(三)
41 0
|
5天前
|
Web App开发 JavaScript 前端开发
程序员必知:【three.js练习程序】创建地球贴图
程序员必知:【three.js练习程序】创建地球贴图
14 0
|
3天前
|
缓存 JavaScript 前端开发
老程序员分享:js刷新页面得重新加载和页面的刷新
老程序员分享:js刷新页面得重新加载和页面的刷新
|
4天前
|
缓存 JavaScript 前端开发
程序员必知:广告等第三方应用嵌入到web页面方案之使用js片段
程序员必知:广告等第三方应用嵌入到web页面方案之使用js片段
|
4天前
|
JavaScript 前端开发 IDE
程序员必知:WPSJSA宏编程(JS):1.初识
程序员必知:WPSJSA宏编程(JS):1.初识
10 0
|
4天前
|
JavaScript 程序员 索引
老程序员分享:JS基础知识(正则)
老程序员分享:JS基础知识(正则)
|
4天前
|
JavaScript 前端开发 小程序
老程序员分享:js中自然日的计算
老程序员分享:js中自然日的计算
|
4天前
|
JavaScript 程序员
老程序员分享:js实现复选框的全选、全部选和反选
老程序员分享:js实现复选框的全选、全部选和反选