I Want to Get Year, Month, Day, etc from Java Date to Compare with Gregorian Calendar Date in Java. Is This Possible

I want to get Year, Month, Day, etc from Java Date to compare with Gregorian Calendar date in Java. Is this possible?

Use something like:

Date date; // your date
// Choose time zone in which you want to interpret your Date
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Europe/Paris"));
cal.setTime(date);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
// etc.

Beware, months start at 0, not 1.

Edit: Since Java 8 it's better to use java.time.LocalDate rather than java.util.Calendar. See this answer for how to do it.

How to extract day, month and year from Date using Java?

Don't use Date as it is deprecated. Use LocalDate and DateTimeFormatter as follows.

LocalDate ld  = LocalDate.parse("2020/05/06", 
DateTimeFormatter.ofPattern("yyyy/MM/dd"));
int year = ld.getYear();
int month = ld.getMonthValue();
int day = ld.getDayOfMonth();
System.out.println(month + " " + day + " " + year);

Prints

5 6 2020

Check out the other date/time related classes in the java.time package.

Trying to compare todays date to given date from HTML

tl;dr

LocalDate 
.parse(
"2022-05-24"
)
.isEqual(
LocalDate
.now(
ZoneId.of( "America/Edmonton" )
)
)

Avoid legacy classes

Do not use Calendar, Date, SimpleDateFormat classes. These terrible classes were years ago supplanted by the modern java.time classes defined in JSR 310.

Compare objects, not text

Do not compare dates as text. Compare objects instead.

LocalDate

Parse your textual input into a LocalDate if you are working with date-only, without time of day, and without time zone.

ISO 8601

Apparently your input string is in standard ISO 8601 format, YYYY-MM-DD. If so, no need to specify a formatting pattern.

String input = "2022-05-24" ;
LocalDate ld = LocalDate.parse( input ) ;

Capture the current date. Time zone is crucial here. For example, at the same simultaneous moment it can be tomorrow in Tokyo Japan while yesterday in Toledo Ohio US.

ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
LocalDate today = LocalDate.now( z ) ;

LocalDate#isEqual

Compare.

boolean isToday = ld.isEqual( today ) ; 

All this has been covered many times already on Stack Overflow. Search to learn more.

java - compare two date values for the month and year

tl;dr

match two dates and if their month/year are same

Is there any other better way to do this comparison?

Yes, the better way uses the modern java.time classes.

YearMonth.from(                                   // Represent the year-month without a day-of-month, without a time-of-day, and without a time zone.
LocalDate.of( 2018 , Month.JANUARY , 23 ) , // Represent a date-only, without a time-of-day and without a time zone.
) // Returns a `YearMonth` object.
.equals( // Compare one `YearMonth` object to another.
YearMonth.now() // Capture today’s year-month as seen in the JVM’s current default time zone.
)

Details

Yes, there is a better way.

You are using old date-time classes bundled with the earliest versions of Java. These classes have proven to be poorly designed, confusing, and troublesome. Avoid them, including java.util.Date.

java.time

Those old classes have been supplanted by the java.time framework built into Java 8 and later.

Instant

Convert the given java.util.Date objects to Instant objects, a moment on the timeline in UTC.

Instant i1 = myJavaUtilDate1.toInstant();
Instant i2 = myJavaUtilDate2.toInstant();

We are aiming to get to YearMonth objects as you only care about the year and the month. But to get there we need to apply a time zone. The year and the month only have meaning in the context of a specific time zone, and unless you are from Iceland I doubt you want the year/month context of UTC.

ZoneId

So we need to specify the desired/expected time zone (ZoneId).

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

ZonedDateTime

Apply that time zone to each Instant, producing ZonedDateTime objects.

ZonedDateTime zdt1 = ZonedDateTime.ofInstant( i1 , zoneId );
ZonedDateTime zdt2 = ZonedDateTime.ofInstant( i2 , zoneId );

YearMonth

Now extract YearMonth objects.

YearMonth ym1 = YearMonth.from( zdt1 );
YearMonth ym2 = YearMonth.from( zdt2 );

Compare.

Boolean same = ym1.equals( ym2 );

By the way, you likely have other business logic involving the year and month. Remember that the java.time classes are built into Java now. So you can use and pass YearMonth objects throughout your code base rather than re-calculating or passing strings.


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?

  • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.

    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

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.

Remaining days taking one date as a reference in Java

Determine a year by comparing the date portion of the current and reference dates. If the date has passed already, use next year; otherwise, use the current year. Then combine this year with the month and day of month from the reference date to yield the anniversary. Finally, compute the difference in days between the reference date and the anniversary.

static LocalDate nextAnniversary(LocalDate date, LocalDate today) {
MonthDay anniversary = MonthDay.from(date);
int year = today.getYear();
if (anniversary.isBefore(MonthDay.from(today))) year += 1;
return anniversary.atYear(year);
}

An example of this function in use:

LocalDateTime stored = LocalDateTime.of(LocalDate.of(2020, 3, 14), LocalTime.NOON);
LocalDate today = LocalDate.now(); /* Or, better: LocalDate.now(clock) */
LocalDate anniversary = nextAnniversary(stored, today);
long daysUntil = today.until(stored, ChronoUnit.DAYS);

Update: This took a few tries to get right. Leap day complicates things; it is best to determine the year first, then to combine it with the original month and day, rather than to increment a past date by one year. (h/t Basil Bourque and Ole V.V.)



Related Topics



Leave a reply



Submit