/**
* 获取两个日期相差天数
*/
function getDays(time1, time2) {
if(typeof time1 === 'string') {
time1 = parse(time1);
}
if(typeof time2 === 'string') {
time2 = parse(time2);
}
return parseInt(Math.abs(time1.getTime() - time2.getTime()) / (1000 * 60 * 60 * 24));
}
//将num左补0为len长度的字符串
function lpadNum(num, len) {
var l = num.toString().length;
while(l < len) {
num = "0" + num;
l++;
}
return num;
}
/**
* 将字符串时间转换成 Date
*/
function parse(str) {
// 这里需要将'-'替换成'/' 因为年-月-日 这种格式解析出来会有问题
return new Date(str.replace(/-/g, "/"));
}
/**
* 将Date解析成字符串
*/
function formatDateTime(time) {
if(typeof time === 'string') {
time = parse(time);
}
return yyyymmdd(time) + " " + hhmmss(time)
}
function yyyymmdd(time, joinStr = '-') {
if(typeof time === 'string') {
time = parse(time);
}
let year = time.getFullYear();
let month = time.getMonth() + 1;
let date = time.getDate();
return year + joinStr + lpadNum(month,2) + joinStr + lpadNum(date,2);
}
function hhmmss(time) {
if(typeof time === 'string') {
time = parse(time);
}
let hours = time.getHours();
let minutes = time.getMinutes();
let seconds = time.getSeconds();
return lpadNum(hours,2) + ":" + lpadNum(minutes,2) + ":" + lpadNum(seconds,2);
}
function hhmm(time) {
if(typeof time === 'string') {
time = parse(time);
}
let hours = time.getHours();
let minutes = time.getMinutes();
return lpadNum(hours,2) + ":" + lpadNum(minutes,2);
}
function showSimpleTime(time) {
// 如果传的是字符串, 则需要将其解析成Date类型
if(typeof time === 'string') {
time = parse(time);
}
let nowDate = new Date();
let fullYear = time.getFullYear();
let month = time.getMonth() + 1;
let date = time.getDate();
let hours = time.getHours();
let minutes = time.getMinutes();
// 判断 当前时间的凌晨 与 传入时间的凌晨 相差多少天
let dayCount = getDays(parse(yyyymmdd(time)), parse(yyyymmdd(nowDate)));
// 同一天
if(dayCount === 0) {
return lpadNum(hours,2) + ":" + lpadNum(minutes, 2);
}
// 是否是昨天
if (dayCount === 1) {
return "昨天 " + lpadNum(hours,2) + ":" + lpadNum(minutes, 2);
}
// 是否是前天
if (dayCount === 2) {
return "前天 " + lpadNum(hours,2) + ":" + lpadNum(minutes, 2);
}
// 同一年
if(fullYear === nowDate.getFullYear()) {
return month + "/" + date + " " + lpadNum(hours,2) + ":" + lpadNum(minutes, 2);
}
return fullYear + "/" + month + "/" + date;
}
js日期处理
最新推荐文章于 2024-08-22 14:32:34 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)