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;
},