格式化时间的方法集合

本文介绍了JavaScript中格式化时间的多种方法,包括使用补零函数和ES6的padStart方法,以及获取当前时间距初始时间的时间戳。此外,还展示了倒计时的实现案例,以及复杂时间格式化的正则表达式处理。这些技巧在前端开发中常用于时间显示和动态计时功能。
摘要由CSDN通过智能技术生成

1、使用补零函数进行格式化


1. 封装时间格式化函数
//定义格式化时间的函数
function formatDate(dateStr) {
    const date = new Date(dateStr)
    const year = date.getFullYear()
    const month = padZero(date.getMonth() + 1)
    const day = padZero(date.getDate())
    const h = padZero(date.getHours())
    const m = padZero(date.getMinutes())
    const s = padZero(date.getSeconds())
    return `${year}-${month}-${day} ${h}:${m}:${s}`
}

//补零函数
function padZero(n) {
    return n < 10 ? '0' + n : n
}

2、使用ES6语法之padStart(方法)

const formatDate = function (v) {
  let date = new Date(v)
  if (Number.isNaN(Number(date))) {
    date = new Date()
  }
  let y = date.getFullYear()
  let mon = (date.getMonth() + 1 + '').padStart(2, '0')
  let d = (date.getDate() + '').padStart(2, '0')
  let h = (date.getHours() + '').padStart(2, '0')
  let min = (date.getMinutes() + '').padStart(2, '0')
  let s = (date.getSeconds() + '').padStart(2, '0')
  return [y, mon, d].join('-') + ' ' + [h, min, s].join(':')
}

3、获取当前时间距离初始时间的时间戳

// 获得系统时间
let date = new Date()
console.log(date) // Thu Apr 28 2022 17:34:10 GMT+0800 (中国标准时间)
// 距离1970年1月1日 过了多少秒   获得总的毫秒数(时间戳)
// 通过valueOf()    getTime()
let date3 = new Date();
console.log(date3.valueOf())
console.log(date3.getTime())
// 简单写法
let date4 = +new Date(); //+new Date(); 就是获取总的毫秒数
console.log(date4)
// H5新增的方法
 console.log(Date.now())

Date.parse()把字符串转换为Date对象 ,然后返回此Date对象与'1970/01/01 00:00:00'之间的毫秒值
(北京时间的时区为东8区,起点时间实际为:'1970/01/01 08:00:00')
Date.parse('2022-2-28')

// 35天后是周几
let fn4 = () => {
let date = new Date()
let day = date.getDate()
console.log(day)
date.setDate(day + 35)
console.log(date)
 }
fn4()

4、适用于倒计时案例

//倒计时案例
countDown() //先调用一次这个函数,防止刷新的时候有空白
setInterval(countDown, 1000)
// 日期的格式化
function countDown(v) {
   let inputTime = +new Date('2023-5-5 17:00:00'); //返回的是用户输入时间的总的毫秒数
   let nowTime = +new Date(); //返回的是当前时间总的毫秒数
   let times = (inputTime - nowTime) / 1000; //times是剩余时间总的秒数
   d = (parseInt(times / 60 / 60 / 24) + '').padStart(2, '0') //天
   h = (parseInt(times / 60 / 60 % 24) + '').padStart(2, '0') //时
   m = (parseInt(times / 60 % 60) + '').padStart(2, '0') //分
   s = (parseInt(times % 60) + '').padStart(2, '0') //秒
   let str = d + '天' + h + '时' + m + '分' + s + '秒'
   box.innerHTML = str
   }

5、复杂格式化时间结合正则

// 时间格式化
  dateFormat(time, fmt) {
    if (!time) return ''
    if (typeof time === 'string' && time.includes('T')) {
      time = time.replace('T', ' ').replace(/\-/g, '/');
    };

    time = new Date(time);
    var o = {
      'M+': time.getMonth() + 1,
      'd+': time.getDate(),
      'h+': time.getHours(),
      'm+': time.getMinutes(),
      's+': time.getSeconds(),
      'q+': Math.floor((time.getMonth() + 3) / 3),
      'S': time.getMilliseconds()
    }

    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (time.getFullYear() + '').substr(4 - RegExp.$1.length))
    for (var 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;
  },

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值