简体   繁体   English

今天即将到期的Java日期

[英]Expiring date today in Java

我需要检查给定日期是否在今天23:59:59之后,如何创建今天23:59:59的日期对象?

Use java.util.Calendar : 使用java.util.Calendar

Calendar cal = Calendar.getInstance(); // represents right now, i.e. today's date
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
cal.set(Calendar.MILLISECOND, 999); // credit to f1sh

Date date = cal.getTime();

I think you might be approaching this from slightly the wrong angle, though. 不过,我认为你可能会从一个错误的角度接近这个。 Instead of trying to create a Date instance that's one atom before midnight, a better approach might be to create the Date that represents midnight and testing whether the current time is strictly less than it. 而不是尝试在午夜之前创建一个原子的Date实例,更好的方法可能是创建表示午夜的Date并测试当前时间是否严格小于它。 I believe this would be slightly clearer in terms of your intentions to someone else reading the code too. 我相信,就你对其他人阅读代码的意图而言,这会更加清晰。


Alternatively, you could use a third-party Date API that knows how to convert back to date. 或者,您可以使用知道如何转换回日期的第三方Date API。 Java's built-in date API is generally considered to be deficient in many ways. Java的内置日期API通常被认为在许多方面存在缺陷。 I wouldn't recommend using another library just to do this, but if you have to do lots of date manipulation and/or are already using a library like Joda Time you could express this concept more simply. 我不建议使用另一个库来执行此操作,但如果您必须进行大量日期操作和/或已经使用像Joda Time这样的库,您可以更简单地表达这个概念。 For example, Joda Time has a DateMidnight class that allows much easier comparison against "raw" dates of the type you're doing, without the possibility for subtle problems (like not setting the milliseconds in my first cut). 例如,Joda Time有一个DateMidnight类,它允许更容易地比较你正在进行的类型的“原始”日期,而不会出现细微的问题(比如在我的第一次剪切中没有设置毫秒)。

This creates a date in the future and compares it with the current date (set to late evening). 这将在未来创建一个日期,并将其与当前日期(设置为深夜)进行比较。 You should consider using the Joda Time Library. 您应该考虑使用Joda时间库。

long timeStampOfTomorrow = new Date().getTime() + 86400000L;
Date dateToCheck = new Date(timeStampOfTomorrow);


Calendar today = Calendar.getInstance();
today.set(Calendar.HOUR_OF_DAY, 23);
today.set(Calendar.MINUTE, 59);
today.set(Calendar.SECOND, 59);
today.set(Calendar.MILLISECOND, 999);

boolean isExpired = dateToCheck.after(today.getTime());

With Joda Time Library you could do this more readable. 使用Joda Time Library,您可以更加可读。 An easy example can be found on the project website . 可以在项目网站上找到一个简单的例子。

public boolean isRentalOverdue(DateTime datetimeRented) {
    Period rentalPeriod = new Period().withDays(2).withHours(12);
    return datetimeRented.plus(rentalPeriod).isBeforeNow();
}

Use the Date.before(Date) or Date.after(Date) 使用 Date.before(Date)或Date.after(Date)

Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, 23);
c.set(Calendar.SECOND, 59);
c.set(Calendar.MINUTE, 59);

Date d = c.getTime()

Date x = // other date from somewhere

x.after(d);

Find the tomorrow date convert it into millisecond you get a long value. 找到明天的日期将其转换为毫秒,你得到一个很长的价值。 subtract -1 from it and again convert to date you will get your required date. 从中减去-1并再次转换为日期,您将获得所需的日期。

ex : 12:00:00 of tomorrow convert it into milliseconds. 例如:明天的12:00:00将其转换为毫秒。 you will get like a long value 312313564774 subtract -1 you will get today eod time in milliseconds 你会得到一个很长的值312313564774减去-1你将得到今天的时间以毫秒为单位

I assume you meant “is the given java.util.Date after today?”. 我假设你的意思是“今天之后是给定的java.util.Date吗?”。

If so, do not fret about determining the last moment of the day; 如果是这样,请不要担心确定当天的最后一刻; that is impracticable because of the fractional second. 由于分数秒,这是不切实际的。 Better to focus on the date only, without the time-of-day. 最好只关注日期,而不是一天中的时间。 You want to know if the date-only of the given moment is after the date-only of the current moment. 您想知道给定时刻的仅日期是否仅在当前时刻的日期之后。 A time zone is crucial here. 时区在这里至关重要。

tl;dr TL;博士

ZoneId z = ZoneId.of( “America/Montreal” );  // Time zone determines date.
Boolean givenMomentIsAfterToday = myUtilDate.toInstant().atZone( z ).toLocalDate().isAfter( LocalDate.now( z ) );

Details 细节

You are using troublesome old date-time classes now supplanted by the java.time classes. 您正在使用现在由java.time类取代的麻烦的旧日期时间类。

First, convert the given java.util.Date to an Instant . 首先,将给定的java.util.Date转换为Instant Find new conversion methods added to the old classes for converting to/from java.time types. 查找添加到旧类的新转换方法,以便转换为/从java.time类型转换。

Instant

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds . Instant类表示UTC时间轴上的一个时刻,分辨率为纳秒

Instant instant = myUtilDate.toInstant();

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone. LocalDate类表示没有时间且没有时区的仅日期值。

A time zone is crucial in determining a date. 时区对于确定日期至关重要。 For any given moment, the date varies 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. 例如,法国巴黎午夜过后几分钟是新的一天,而在魁北克蒙特利尔仍然是“昨天”。

ZoneId z = ZoneId.of( “America/Montreal” );
LocalDate today = LocalDate.now( z );

ZonedDateTime

Adjust the instant into the same time zone for comparison of dates. 将瞬间调整到相同的时区以进行日期比较。

ZonedDateTime zdt = instant.atZone( z );

Interrogate for the date-only value, a LocalDate . 询问仅限日期的值,即LocalDate

LocalDate ldt = zdt.toLocalDate();

Lastly, compare the LocalDate objects. 最后,比较LocalDate对象。

Boolean givenMomentIsAfterToday = ldt.isAfter( today );

About java.time 关于java.time

The java.time framework is built into Java 8 and later. java.time框架内置于Java 8及更高版本中。 These classes supplant the troublesome old date-time classes such as java.util.Date , .Calendar , & java.text.SimpleDateFormat . 这些类取代了麻烦的旧日期时间类,如java.util.Date.Calendarjava.text.SimpleDateFormat

The Joda-Time project, now in maintenance mode , advises migration to java.time. 现在处于维护模式Joda-Time项目建议迁移到java.time。

To learn more, see the Oracle Tutorial . 要了解更多信息,请参阅Oracle教程 And search Stack Overflow for many examples and explanations. 并搜索Stack Overflow以获取许多示例和解释。

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use… ). 大部分的java.time功能后移植到Java 6和7 ThreeTen,反向移植 ,并进一步适应的AndroidThreeTenABP (见如何使用...... )。

The ThreeTen-Extra project extends java.time with additional classes. ThreeTen-Extra项目使用其他类扩展了java.time。 This project is a proving ground for possible future additions to java.time. 该项目是未来可能添加到java.time的试验场。 You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more. 您可以在这里找到一些有用的课程,如IntervalYearWeekYearQuarter等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM