Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

实现一个函数, 计算两个日期之间的天数差 #567

Open
yanlele opened this issue Sep 24, 2023 · 0 comments
Open

实现一个函数, 计算两个日期之间的天数差 #567

yanlele opened this issue Sep 24, 2023 · 0 comments
Labels
代码实现/算法 代码实现或者算法实现 网易 公司标签
Milestone

Comments

@yanlele
Copy link
Member

yanlele commented Sep 24, 2023

以下是使用JavaScript实现计算两个日期之间的天数差的函数:

function calculateDateDifference(date1, date2) {
  // 将日期字符串转换为 Date 对象
  const d1 = new Date(date1);
  const d2 = new Date(date2);

  // 计算两个日期的时间差(毫秒数)
  const timeDiff = Math.abs(d2.getTime() - d1.getTime());

  // 将时间差转换为天数
  const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24));

  return daysDiff;
}

// 示例用法
const date1 = '2022-01-01';
const date2 = '2022-01-10';

const difference = calculateDateDifference(date1, date2);
console.log(difference); // 输出结果为 9

上述函数首先将两个日期字符串转换为Date对象,然后计算两个日期对象之间的时间差(以毫秒表示),最后将时间差转换为天数。通过调用calculateDateDifference函数,可以获取两个日期之间的天数差。

@yanlele yanlele added 代码实现/算法 代码实现或者算法实现 网易 公司标签 labels Sep 24, 2023
@yanlele yanlele added this to the milestone Sep 24, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
代码实现/算法 代码实现或者算法实现 网易 公司标签
Projects
None yet
Development

No branches or pull requests

1 participant