仅比较两个日期的时间部分,而忽略日期部分 [英] Compare only the time portion of two dates, ignoring the date part

查看:97
本文介绍了仅比较两个日期的时间部分,而忽略日期部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定两个Date对象,仅比较它们的时间部分之间的差异,而完全忽略Year,Month和Day,这是什么好方法呢?



相反



将您的 java.util.Date (以UTC表示的时间)转换为即时。使用新的转换方法添加到旧类中。

  Instant Instant = myJavaUtilDate.toInstant(); 

这代表着UTC的时刻。确定日期和时间需要



> ThreeTen-Extra 项目通过其他类扩展了java.time。该项目为将来可能在java.time中添加内容打下了基础。您可能会在这里找到一些有用的类,例如 时间间隔 YearWeek YearQuarter 更多


What's a good method to, given two Date objects, compare the difference between their time portion only, completely ignoring Year, Month and Day?

It's quite the opposite of this question.

UPDATE: Here's the final code for future reference:

private long differenceBetween(Date currentTime, Date timeToRun)
{
    Calendar currentCal = Calendar.getInstance();
    currentCal.setTime(currentTime);

    Calendar runCal = Calendar.getInstance();
    runCal.setTime(timeToRun);
    runCal.set(Calendar.DAY_OF_MONTH, currentCal.get(Calendar.DAY_OF_MONTH));
    runCal.set(Calendar.MONTH, currentCal.get(Calendar.MONTH));
    runCal.set(Calendar.YEAR, currentCal.get(Calendar.YEAR));

    return currentCal.getTimeInMillis() - runCal.getTimeInMillis();
}

解决方案

tl;dr

Duration                                  // Span of time, with resolution of nanoseconds.
.between(                                 // Calculate elapsed time.
    LocalTime.now(                        // Get current time-of-day…
        ZoneId.of( "Pacific/Auckland" )   // … as seen in a particular time zone.
    )                                     // Returns a `LocalTime` object.
    ,
    myJavaUtilDate                        // Avoid terrible legacy date-time classes such as `java.util.Date`.
    .toInstant()                          // Convert from `java.util.Date` to `java.time.Instant`, both representing a moment in UTC.
    .atZone(                              // Adjust from UTC to a particular time zone. Same moment, same point on the timeline, different wall-clock time.
        ZoneId.of( "Pacific/Auckland" )   // Specify time zone by proper naming in `Continent/Region` format, never 2-4 letter pseudo-zones such as `PST`, `CEST`, `CST`, `IST`, etc.
    )                                     // Returns a `ZonedDateTime` object.
    .toLocalTime()                        // Extract the time-of-day without the date and without a time zone.
)                                         // Returns a `Duration` object.
.toMillis()                               // Calculate entire span-of-time in milliseconds. Beware of data-loss as `Instant` uses a finer resolution the milliseconds, and may carry microseconds or nanoseconds.

I suggest passing around the type-safe and self-explanatory Duration object rather than a mere integer number of milliseconds.

java.time

The modern approach uses the java.time classes that supplanted the terrible legacy classes such as Date, Calendar, SimpleDateFormat.

Convert your java.util.Date (a moment in UTC), to an Instant. Use new conversion methods added to the old classes.

Instant instant = myJavaUtilDate.toInstant() ;

That represents a moment in UTC. Determining a date and a time-of-day requires a time zone . For any given moment, the date and time vary around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still "yesterday" in Montréal Québec.

If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" ) ;  

If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.

ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.

Assign the ZoneId to the Instant to produce a ZonedDateTime object.

ZonedDateTime zdt = instant.atZone( z ) ;

Extract the time-of-day portion, without the date and without the time zone.

LocalTime lt = zdt.toLocalTime() ;

Compare. Calculate elapsed time with a Duration.

Duration d = Duration.between( ltStart , ltStop ) ;

Be aware that this is not a fair comparison. Days are not always 24-hours long, and not all time-of-day values are valid on all days in all zones. For example, in the United States during a Daylight Saving Time cutover, there may not be a 2 AM hour at all. So 1 AM to 4 AM may be 3 hours on one date but only 2 hours on another date.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

这篇关于仅比较两个日期的时间部分,而忽略日期部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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