首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何计算两个日期之间的天数?

如何计算两个日期之间的天数?
EN

Stack Overflow用户
提问于 2010-04-13 14:37:51
回答 7查看 445.9K关注 0票数 314
  1. 我正在计算“from”和“to”日期之间的天数。例如,如果开始日期是13/04/2010,结束日期是15/04/2010,则结果应为
  2. How do I get the result using JavaScript?
EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2010-04-13 14:42:02

代码语言:javascript
复制
const oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
const firstDate = new Date(2008, 1, 12);
const secondDate = new Date(2008, 1, 22);

const diffDays = Math.round(Math.abs((firstDate - secondDate) / oneDay));
票数 649
EN

Stack Overflow用户

发布于 2010-04-13 14:39:54

下面是一个执行此操作的函数:

代码语言:javascript
复制
function days_between(date1, date2) {

    // The number of milliseconds in one day
    const ONE_DAY = 1000 * 60 * 60 * 24;

    // Calculate the difference in milliseconds
    const differenceMs = Math.abs(date1 - date2);

    // Convert back to days and return
    return Math.round(differenceMs / ONE_DAY);

}
票数 56
EN

Stack Overflow用户

发布于 2013-07-18 23:37:32

下面是我使用的代码。如果只减去日期,它将无法跨越夏令时界限(例如,4月1日至4月30日或10月1日至10月31日)。这减少了所有小时,以确保您有一天,并通过使用UTC消除了任何DST问题。

代码语言:javascript
复制
var nDays = (    Date.UTC(EndDate.getFullYear(), EndDate.getMonth(), EndDate.getDate()) -
                 Date.UTC(StartDate.getFullYear(), StartDate.getMonth(), StartDate.getDate())) / 86400000;

作为函数:

代码语言:javascript
复制
function DaysBetween(StartDate, EndDate) {
  // The number of milliseconds in all UTC days (no DST)
  const oneDay = 1000 * 60 * 60 * 24;

  // A day in UTC always lasts 24 hours (unlike in other time formats)
  const start = Date.UTC(EndDate.getFullYear(), EndDate.getMonth(), EndDate.getDate());
  const end = Date.UTC(StartDate.getFullYear(), StartDate.getMonth(), StartDate.getDate());

  // so it's safe to divide by 24 hours
  return (start - end) / oneDay;
}
票数 31
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2627473

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档