博客
关于我
JS日期格式转换
阅读量:466 次
发布时间:2019-03-06

本文共 1835 字,大约阅读时间需要 6 分钟。

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。

// 日期格式化1function parseTimeNew (date) {    var ndate = new 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}

使用方法:

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

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

new Date(time).getTime()

使用方法:

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

 3.判断日期是否为昨天

// 判断日期是否为昨天function isYestday (theDate) {      let date = (new Date())// 当前时间      let today = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime()      // 今天凌晨      let yestday = new Date(today - 24 * 3600 * 1000).getTime()      return theDate.getTime() < today && yestday <= 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分的时间戳

let 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

 

转载地址:http://hagfz.baihongyu.com/

你可能感兴趣的文章
MySQL 查询优化:提速查询效率的13大秘籍(避免使用SELECT 、分页查询的优化、合理使用连接、子查询的优化)(上)
查看>>
mysql 查询数据库所有表的字段信息
查看>>
【Java基础】什么是面向对象?
查看>>
mysql 查询,正数降序排序,负数升序排序
查看>>
MySQL 树形结构 根据指定节点 获取其下属的所有子节点(包含路径上的枝干节点和叶子节点)...
查看>>
mysql 死锁 Deadlock found when trying to get lock; try restarting transaction
查看>>
mysql 死锁(先delete 后insert)日志分析
查看>>
MySQL 死锁了,怎么办?
查看>>
MySQL 深度分页性能急剧下降,该如何优化?
查看>>
MySQL 深度分页性能急剧下降,该如何优化?
查看>>
MySQL 添加列,修改列,删除列
查看>>
mysql 添加索引
查看>>
MySQL 添加索引,删除索引及其用法
查看>>
mysql 状态检查,备份,修复
查看>>
MySQL 用 limit 为什么会影响性能?
查看>>
MySQL 用 limit 为什么会影响性能?有什么优化方案?
查看>>
MySQL 用户权限管理:授权、撤销、密码更新和用户删除(图文解析)
查看>>
mysql 用户管理和权限设置
查看>>
MySQL 的 varchar 水真的太深了!
查看>>
mysql 的GROUP_CONCAT函数的使用(group_by 如何显示分组之前的数据)
查看>>