zoukankan      html  css  js  c++  java
  • 日期格式转换

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

    new Date()//转换成标准日期格式

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

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

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

    function DateFormat (date, fmt) {//要转换的date日期,fmt返回的格式
      let 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 (let 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
    }

    引用方法

    DateFormat(1535760000000, 'yyyy-MM-dd')//将前面的数字日期的格式转换成yyyy-MM-dd样式
    DateFormat(1535760000000, 'yyyy-MM-dd hh:mm:ss')//将前面的数字日期的格式转换成yyyy-MM-dd hh:mm:ss样式2

    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
  • 相关阅读:
    iPhone6虽好,但也要借鉴这八个功能
    中小型企业商业智能平台的开发和实现(数据仓库、BI系统、真实项目实战)
    iOS开发入门教程_iOS开发视频教程
    零基础入门jQuery视频教程
    零基础3G Android移动开发就业培训
    请求库requesets库使用
    请求头加引号工具
    请求库urllib使用
    【Liunx】saltstack运维工具
    【Liunx】消息队列rabbitmp
  • 原文地址:https://www.cnblogs.com/wgl0126/p/10687977.html
Copyright © 2011-2022 走看看