如何判断两个日期是在同一天还是同一小时? [英] How to tell if two dates are in the same day or in the same hour?

查看:66
本文介绍了如何判断两个日期是在同一天还是同一小时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript Date 对象将日期与时间进行比较,因此,如果您比较:time1.getTime() === time2.getTime(),如果至少一毫秒不同,它们将是false".

The JavaScript Date object compare dates with time including, so, if you compare: time1.getTime() === time2.getTime(), they'll be "false" if at least one millisecond is different.

我们需要的是有一个很好的方法来按小时、天、周、月、年进行比较?其中一些很简单,比如 year:time1.getYear() === time2.getYear()但对于日、月、小时,则更为复杂,因为它需要多次验证或划分.

What we need is to have a nice way to compare by Hour, Day, Week, Month, Year? Some of them are easy, like year: time1.getYear() === time2.getYear() but with day, month, hour it is more complex, as it requires multiple validations or divisions.

是否有任何不错的模块或优化的代码来进行这些比较?

Is there any nice module or optimized code for doing those comparisons?

推荐答案

Date 原型具有 API,可让您查看年、月和月中的某天,这看起来简单而有效.

The Date prototype has APIs that allow you to check the year, month, and day-of-month, which seems simple and effective.

您需要从代码运行的语言环境的角度来决定您的应用程序是否需要相同的日期,或者是否应该基于 UTC 值进行比较.

You'll want to decide whether your application needs the dates to be the same from the point of view of the locale where your code runs, or if the comparison should be based on UTC values.

function sameDay(d1, d2) {
  return d1.getFullYear() === d2.getFullYear() &&
    d1.getMonth() === d2.getMonth() &&
    d1.getDate() === d2.getDate();
}

对应的UTC gettergetUTCFullYear()getUTCMonth()getUTCDate().

There are corresponding UTC getters getUTCFullYear(), getUTCMonth(), and getUTCDate().

这篇关于如何判断两个日期是在同一天还是同一小时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆