Expires Today in Java

I need to check if the set date after today was 23:59:59, how can I create a date object that is 23:59:59 today?

+5
source share
5 answers

Use java.util.Calendar :

Calendar cal = Calendar.getInstance(); // represents right now, i.e. today 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 a slightly wrong angle. Instead of trying to create an instance of Date that is one atom before midnight, a better approach would be to create a date representing midnight and check if the current time is strictly less. I believe this will be a little clearer in terms of your intentions for someone else to read the code too.


API- , , . API- Java, , . , / , Joda Time . , Joda Time DateMidnight, "" , , (, ).

+3

( ). 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());

Joda . - .

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

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);
0

, , long. -1 , .

ex: 12:00:00 .     312313564774     -1, eod time

0

, " java.util.Date ?".

, ; - . , . , . .

TL;DR

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

, java.time.

java.util.Date Instant. , / java.time.

Instant

Instant UTC .

Instant instant = myUtilDate.toInstant();

LocalDate

LocalDate .

. . , - , "" .

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

ZonedDateTime

.

ZonedDateTime zdt = instant.atZone( z );

, a LocalDate.

LocalDate ldt = zdt.toLocalDate();

, LocalDate.

Boolean givenMomentIsAfterToday = ldt.isAfter( today );

java.time

java.time Java 8 . , java.util.Date, .Calendar java.text.SimpleDateFormat.

Joda-Time, , java.time.

, . Oracle. Qaru .

java.time Java 6 7 ThreeTen-Backport Android ThreeTenABP (. ...).

ThreeTen-Extra java.time . java.time. , Interval, YearWeek, YearQuarter ..

0

All Articles