javascript - 在javascript中按天比较两个日期
问题描述
我试图在javascript中比较两个日期。比较日期很好,但我只想按天比较它们而忽略一天中的时间。如果不依赖像momentjs这样的库,这可能吗?
解决方案
这是一个比较没有时间的日期的片段:
var today = new Date();
today.setHours(0, 0, 0, 0);
d = new Date(my_value);
d.setHours(0, 0, 0, 0);
if(d >= today){
alert(d is greater than or equal to current date);
}
这是一个函数,可以为您提供两天之间的确切差异:
function daysBetween(first, second) {
// Copy date parts of the timestamps, discarding the time parts.
var one = new Date(first.getFullYear(), first.getMonth(), first.getDate());
var two = new Date(second.getFullYear(), second.getMonth(), second.getDate());
// Do the math.
var millisecondsPerDay = 1000 * 60 * 60 * 24;
var millisBetween = two.getTime() - one.getTime();
var days = millisBetween / millisecondsPerDay;
// Round down.
return Math.floor(days);
}
推荐阅读
- python - 子流程 | 脚本到脚本连续输入/输出
- windows - 为什么 Windows 有 5-7 种不同的内存分配例程?
- php - Laravel中图像路径中的正斜杠问题
- ios - 无法从日期扩展的功能分配给 Int
- java - 使用自定义比较器查找数组列表的最大值
- dart - 使用 ML Kit 的计算机视觉 - Flutter In Focus
- java - 我可以在基于 Java 的 heroku 应用程序中使用本机应用程序吗?
- tableau-api - 如何在 Tableau 中制作具有 2 个度量的 100% 堆叠图表?
- android - Android Recycler View Item 布局问题
- html - Bootstrap 容器上的宽图像