时间转换函数
持续更新
1. 获取当前时间戳
+new Date()
2. 获取中国标准时间格式
new Date()
3. 格式化时间
2023-02-23 格式
输入:中国标准时间
输出:2023-02-23 格式
// 输入:中国标准时间
// 输出:2023-02-23 格式
function timestampToTime (date) {
const Y = date.getFullYear() + '-'
const M =
(date.getMonth() + 1 < 10
? '0' + (date.getMonth() + 1)
: date.getMonth() + 1) + '-'
const D =
(date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
return Y + M + D
}
2023-02-23 17:22:57 格式
输入:中国标准时间
输出:2023-02-23 17:22:57 格式
// 输入:中国标准时间
// 输出:2023-02-23 17:22:57 格式
function timestampToTimeWith () {
var date = new Date();
var Y = date.getFullYear() + '-';
var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
return Y + M + D + h + m + s;
}
4.计算时间
使用时间戳计算距离现在的时间有多久
- 输入:时间戳
输出: 刚刚/m分钟前/h小时前/1天前
// 输入:时间戳
// 输出: 刚刚/m分钟前/h小时前/1天前
function formatTime (time, option) {
if (('' + time).length === 10) {
time = parseInt(time) * 1000
} else {
time = +time
}
const d = new Date(time)
const now = Date.now()
const diff = (now - d) / 1000
if (diff < 30) {
return '刚刚'
} else if (diff < 3600) {
// less 1 hour
return Math.ceil(diff / 60) + '分钟前'
} else if (diff < 3600 * 24) {
return Math.ceil(diff / 3600) + '小时前'
} else if (diff < 3600 * 24 * 2) {
return '1天前'
}
if (option) {
return parseTime(time, option)
} else {
return (
d.getMonth() +
1 +
'月' +
d.getDate() +
'日' +
d.getHours() +
'时' +
d.getMinutes() +
'分'
)
}
}
获取两个日期之间的天数差
- 输入:两段时间戳(任意两段时间戳)
输出: x (天数差)
// 输入:两段时间戳(任意两段时间戳)
// 输出: x (天数差)
function getTimeDay (timeStart, timeEnd) {
let t = parseInt((timeStart - timeEnd) / (24 * 60 * 60 * 1000))
//
t = t < 0 ? -t : t
return t
}