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
  • 相关阅读:
    P1351 联合权值
    c++ 贪心讲解大礼包
    取石子 找规律
    树 dfs暴力判环 题意转化
    P2519 [HAOI2011]problem a
    P1640 [SCOI2010]连续攻击游戏 二分图最大匹配 匈牙利算法
    P2756 飞行员配对方案问题 二分图匹配 匈牙利算法
    cogs 49. 跳马问题 DFS dp
    cogs 2. 旅行计划 dijkstra+打印路径小技巧
    cogs 1440. [NOIP2013]积木大赛 贪心水题
  • 原文地址:https://www.cnblogs.com/wgl0126/p/10687977.html
Copyright © 2011-2022 走看看