0

I have a Calendar object as below where I get the value as below

Calendar qrExpiryDate = 

java.util.GregorianCalendar[time=1651237080000,areFieldsSet=true,areAllFieldsSet=true,lenient=false,zone=sun.util.calendar.ZoneInfo[id="GMT-04:00",offset=-14400000,dstSavings=0,useDaylight=false,transitions=0,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2022,MONTH=3,WEEK_OF_YEAR=18,WEEK_OF_MONTH=5,DAY_OF_MONTH=29,DAY_OF_YEAR=119,DAY_OF_WEEK=6,DAY_OF_WEEK_IN_MONTH=5,AM_PM=0,HOUR=8,HOUR_OF_DAY=8,MINUTE=58,SECOND=0,MILLISECOND=0,ZONE_OFFSET=-14400000,DST_OFFSET=0]

I would like to check if this date is expired or not, by doing a validation using java with the current date. How can I achieve this?

Jens
  • 67,715
  • 15
  • 98
  • 113
P_V_N
  • 9
  • 1
  • 1
    If possible, you should throw [these old classes](https://stackoverflow.com/questions/1571265/why-is-the-java-date-api-java-util-date-calendar-such-a-mess) down the [memory hole](https://en.wikipedia.org/wiki/Memory_hole). – andrewJames May 03 '22 at 20:26
  • I too recommend you don’t use `Calendar`. That class is poorly designed and long outdated. Instead use for example `ZonedDateTime` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). Then `if (ZonedDateTime.now().isAfter(qrExpiryZonedDateTime)) …`. – Ole V.V. May 04 '22 at 06:02
  • If you cannot avoid getting a `Calendar` object from a legacy API, then just `if (Instant.now().isAfter(qrExpiryDate.toInstant())) …`. – Ole V.V. May 04 '22 at 06:09

1 Answers1

1

If you must use the Calendar object, you could do something like like

new Date().before(calendar.getTime());

or

calendar.getTime().after(new Date());

However, the Date() class is mostly deprecated. You should use LocalDateTime or ZonedDateTime

Ryan
  • 1,762
  • 6
  • 11
  • `ZonedDateTime` is a good choice. `LocalDateTime` hardly is since it cannot denote a point in time. And I agree, `Calendar` certainly isn’t, nor `Date`. – Ole V.V. May 04 '22 at 06:05
  • Even if you can’t avoid `Calendar`, there is no reason why you shouldn’t avoid `Date`: `Instant.now().isAfter(calendar.toInstant())`. – Ole V.V. May 04 '22 at 06:22