一:
简单日期格式化 年-月-日
const newDate = (d, str = '-') => {
let year = d.getFullYear()
let month = d.getMonth() + 1
let day = d.getDate()
month < 10 && (month = '0' + month)
day < 10 && (day = '0' + day)
return [year, month, day].join(str)
}
年-月-日 时:分:秒
// 日期格式化, 显示yyyy-mm-dd hh:mm:ss
const newDate = (d, str = '-') => {
let year = d.getFullYear()
let month = d.getMonth() + 1
let day = d.getDate()
let hour = d.getHours()
let minute = d.getMinutes()
let second = d.getSeconds()
month < 10 && (month = '0' + month)
day < 10 && (day = '0' + day)
hour < 10 && (hour = '0' + hour)
minute < 10 && (minute = '0' + minute)
second < 10 && (second = '0' + second)
return [year, month, day].join(str) + ' ' + [hour, minute, second].join(':')
}
直接输出就行
console.log(newDate(new Date()));
二:
-
t>24h,显示xx天xx小时
-
1h<t≤24h,显示xx小时xx分钟
-
t<1h,显示xx分钟
实现思路
function regular(t) {
// 用正则表达式实现,把负号转换成剩余几天
let reg = /^-/
if (reg.test(t)) {
let num = t.replace(/^-/, '')
return `剩余`
}
return '已结束'
}
function fn(data) {
let arr = data.map((item) => {
let time = new Date(item.time)
let now = new Date()
let t = ((now - time) / 1000).toString()
let d = Math.abs(parseInt(t / (24 * 3600)))
let h = Math.abs(parseInt(t / 3600) - d * 24)
let m = Math.abs(parseInt(t / 60) - d * 24 * 60 - h * 60)
if (t > 24 * 3600 || t < -24 * 3600) {
return `${regular(t)}${d}天${h}小时`
} else if (t > 3600 || t < -3600) {
return `${regular(t)}${h}小时${m}分钟`
} else {
return `${regular(t)}${m}分钟`
}
})
return arr
}
测试数据:
let data = [
{
time: '2022-11-11 11:11:11'
},
{
time: '2022-11-10 12:12:12'
},
{
time: '2022-11-14 10:10:10'
},
{
time: '2022-4-29 11:11:11'
},
{
time: '2022-4-27 15:00:00'
},
{
time: '2022-4-26 18:00:00'
}
]
三:
今年内显示mm月dd日,今年之前显示yyyy-mm-dd
代码实现
function fn(data) {
let time = new Date()
return data.map((item) => {
let t = new Date(item.time)
let y = t.getFullYear()
let m = t.getMonth() + 1
let d = t.getDate()
if (y === time.getFullYear()) {
return `${m}月${d}日`
} else {
return `${y}-${m}-${d}`
}
})
}
测试数据:
let data = [
{
time: '2022-11-11 11:11:11',
},
{
time: '2022-11-10 12:12:12',
},
{
time: '2021-11-14 10:10:10',
},
{
time: '2020-4-29 11:11:11',
}
]