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。

// 日期格式化1
function 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()<br>}<br>//调用<br>let time = new Date('2013-11-11')<br>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

 

posted @ 2021-03-17 16:47  快跑啊小卢  阅读(3234)  评论(0)    收藏  举报