计算给定日期距离当前日期过去了多少天

  • Published2025-11-21 02:19:36

function daysPassedSinceDate(dateString) {

// 将日期字符串解析成Date对象

const date = new Date(dateString);

// 获取当前日期

const currentDate = new Date();

// 计算日期差值(单位:毫秒)

const timeDiff = currentDate - date;

// 将毫秒转换为天数

const daysPassed = Math.floor(timeDiff / (1000 * 60 * 60 * 24));

return daysPassed;

};

其中传入的dateString的日期格式为“年-月-日(2023-02-27)”

例:小于三十天,在layui.dtree目录树上添加new小标记

//右上角new小图标

var targetCite = '',targetSpan = '';

//其中dataLoad为对象,数据格式为{{no:'2480',date:'2023-07-25'},{no:'3307',date:'2023-06-03'}...}

$.each(dataLoad, function(i, t) {

if (t.date) {//如果date存在则执行下面的函数

//当前日期距离传入的t.date值已过去多少天,单位为“天”

const daysPassed = daysPassedSinceDate(t.date);

//如果时间小于30天,则在又上角添加new小标记

if (daysPassed <= 30) {

//根据data-id的值定位cite元素

targetCite = $('cite[data-id="' + t.no + '"]');

targetSpan = targetCite.nextAll('#lx').first();

// 判断是否存在span元素

if (targetSpan.length === 0) {

// 如果不存在,添加在cite后面

targetCite.after('new');

} else {

// 如果存在,添加在span后面

targetSpan.after('new');

}

}

}

});

上面的小标记的样式为

#layui-badge {

background-color: #ff5722 !important;

color: #fff;

vertical-align: super;

border-radius: 3px;

display: inline;

padding: 1px 2px;

}