277

I have a Date object in Java stored as Java's Date type.

I also have a Gregorian Calendar created date. The gregorian calendar date has no parameters and therefore is an instance of today's date (and time?).

With the java date, I want to be able to get the year, month, day, hour, minute, and seconds from the java date type and compare the the gregoriancalendar date.

I saw that at the moment the Java date is stored as a long and the only methods available seem to just write the long as a formatted date string. Is there a way to access Year, month, day, etc?

I saw that the getYear(), getMonth(), etc. methods for Date class have been deprecated. I was wondering what's the best practice to use the Java Date instance I have with the GregorianCalendar date.

My end goal is to do a date calculation so that I can check that the Java date is within so many hours, minutes etc of today's date and time.

I'm still a newbie to Java and am getting a bit puzzled by this.

Micho
  • 3,929
  • 13
  • 37
  • 40
daveb
  • 3,465
  • 6
  • 23
  • 28
  • 2
    Hey whatever you use don't use `Date.getYear()` .It suffers from problems(that i don't know).`Date.getYear()` once parsed my date 30/06/2017 and it returned my year as 117. See where it landed, two thousand years back. But when i print simply the Date Object,Output was Fine.But not `Date.getYear();`. – Seeni Jun 30 '17 at 10:26
  • FYI: You are using troublesome old Date-time classes that are now legacy, supplanted by the modern java.time classes. – Basil Bourque Oct 25 '17 at 15:12

8 Answers8

611

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.

Vic Seedoubleyew
  • 9,888
  • 6
  • 55
  • 76
Florent Guillaume
  • 8,243
  • 1
  • 24
  • 25
  • Thank you so much! This is exactly what I want to achieve. I am handling months starting from 0 - 11. If i wanted to check the Java date above is within 48 hours of todays date is it best to subtract 48 hours from my gregorian calendar date instance? – daveb Feb 27 '12 at 23:51
  • 4
    You can use `cal.add(Calendar.DAY_OF_MONTH, -48)` to do day arithmetic on Calendar objects. And you can compare two Calendar objects using `cal.compareTo(anotherCal)`. – Florent Guillaume Feb 27 '12 at 23:55
  • 1
    Brilliant, cheers Florent! Does the above mean the Calender will return updated year and day, seconds, minutes and seconds when the calender get methods are used? Dave – daveb Feb 28 '12 at 00:02
  • 1
    A `Calendar` instance is a mutable object representing an instant on a calendar. Whenever you call a `set*` method on it, the represented instant will change, and `get*` methods will potentially return new values. – Florent Guillaume Feb 28 '12 at 00:06
  • 12
    Note that month starts with 0 and not 1 (ie January=0). http://docs.oracle.com/javase/6/docs/api/java/util/Calendar.html#MONTH – Steve Kuo Feb 28 '12 at 00:33
  • 13
    Why JAVA is so inconvenient? – Kimchi Man Sep 12 '14 at 14:21
  • 3
    Because Date and Calendar are old and badly designed. Java 8 has much better data/time objects, see http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html – Florent Guillaume Sep 12 '14 at 15:20
  • Tnx, vry usful also for me :-) – AndreaNobili Jul 04 '16 at 10:50
  • This Answer has been out of date for years. For the modern solution, see [the correct Answer by Lokni](https://stackoverflow.com/a/32363174/642706) using the java.time classes. @daveb Please consider changing your acceptance. – Basil Bourque Oct 25 '17 at 15:17
  • I've opt to use Calendar compared to LocalDate since some LocaleDate functions require API level 26 which contrasts with my API level 17. – Andrew Chelix Sep 03 '20 at 20:46
123

With Java 8 and later, you can convert the Date object to a LocalDate object and then easily get the year, month and day.

Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
int year  = localDate.getYear();
int month = localDate.getMonthValue();
int day   = localDate.getDayOfMonth();

Note that getMonthValue() returns an int value from 1 to 12.

Ortomala Lokni
  • 56,620
  • 24
  • 188
  • 240
14
    Date date = new Date();

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE");

    System.out.println("DAY "+simpleDateFormat.format(date).toUpperCase());

    simpleDateFormat = new SimpleDateFormat("MMMM");
    System.out.println("MONTH "+simpleDateFormat.format(date).toUpperCase());

    simpleDateFormat = new SimpleDateFormat("YYYY");
    System.out.println("YEAR "+simpleDateFormat.format(date).toUpperCase());

EDIT: The output for date = Fri Jun 15 09:20:21 CEST 2018 is:

DAY FRIDAY
MONTH JUNE
YEAR 2018
SantiBailors
  • 1,596
  • 3
  • 21
  • 44
Az.MaYo
  • 1,044
  • 10
  • 23
  • 1
    If you had put at least the output, people could decide if this might be useful to them or not without having to run the code. – SantiBailors Jun 15 '18 at 07:15
  • 2
    Beware of the case of format pattern letters. Uppercase `YYYY` is incorrect. And we should no longer use `SimpleDateFormat`, it’s a notorious troublemaker of a class. – Ole V.V. Jun 30 '20 at 05:46
  • 1
    Bad answer, if you try to obtain the Year of this Date: new Date(1703998800000L) you will obtain 2024 instead the correct answer 2023 – Alexis Gamarra Sep 06 '22 at 03:49
  • I had to downvote. This doesn't answer the question. It's also wrong for some dates, as explained by Ole and Alexis. – Dawood ibn Kareem Oct 02 '22 at 00:10
14

You could do something like this, it will explain how the Date class works.

String currentDateString = "02/27/2012 17:00:00";
SimpleDateFormat sd = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date currentDate = sd.parse(currentDateString);

String yourDateString = "02/28/2012 15:00:00";
SimpleDateFormat yourDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

Date yourDate = yourDateFormat.parse(yourDateString);

if (yourDate.after(currentDate)) {
    System.out.println("After");
} else if(yourDate.equals(currentDate)) {
    System.out.println("Same");
} else {
    System.out.println("Before");
}
rhavelka
  • 2,283
  • 3
  • 22
  • 36
javaCity
  • 4,288
  • 2
  • 25
  • 37
  • Hi JavaCity, Thanks for this. this is very useful. At the moment I am trying to shy away from parsing from a date string. I will need to do this parsing later on however when I get users of my application to set year, day and month. I was going to build a string to parse into SimpleDateFormat. The above is very useful to see this in action. My Java date was created as a date and time from its instantiation a day ago. I am now looking to compare with the gregoriancalendar date which has been instantiated today. Sincere thanks – daveb Feb 27 '12 at 23:57
  • 8
    Please fix code ... lowercase `mm` indicates minutes, uppercase `MM` means month-of-year. – YoYo May 17 '16 at 02:40
9
private boolean isSameDay(Date date1, Date date2) {
    Calendar calendar1 = Calendar.getInstance();
    calendar1.setTime(date1);
    Calendar calendar2 = Calendar.getInstance();
    calendar2.setTime(date2);
    boolean sameYear = calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR);
    boolean sameMonth = calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH);
    boolean sameDay = calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH);
    return (sameDay && sameMonth && sameYear);
}
evya
  • 3,381
  • 1
  • 25
  • 28
4

It might be easier

     Date date1 = new Date("31-May-2017");
OR
    java.sql.Date date1 = new java.sql.Date((new Date()).getTime());

    SimpleDateFormat formatNowDay = new SimpleDateFormat("dd");
    SimpleDateFormat formatNowMonth = new SimpleDateFormat("MM");
    SimpleDateFormat formatNowYear = new SimpleDateFormat("YYYY");

    String currentDay = formatNowDay.format(date1);
    String currentMonth = formatNowMonth.format(date1);
    String currentYear = formatNowYear.format(date1);
Abdur Rahman
  • 1,420
  • 1
  • 21
  • 32
3
    Date queueDate = new SimpleDateFormat("yyyy-MM-dd").parse(inputDtStr);
    Calendar queueDateCal = Calendar.getInstance();
    queueDateCal.setTime(queueDate);
    if(queueDateCal.get(Calendar.DAY_OF_YEAR)==Calendar.getInstance().get(Calendar.DAY_OF_YEAR))
{
    "same day of the year!";
 }
rabi
  • 91
  • 1
  • 1
    Answers on Stack Overflow are expected to have some discussion and explanation, not just code snippets. And your code could definitely use some explanation. – Basil Bourque Sep 14 '18 at 00:15
  • 1
    FYI, the terribly troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Sep 14 '18 at 00:15
2
@Test
public void testDate() throws ParseException {
    long start = System.currentTimeMillis();
    long round = 100000l;
    for (int i = 0; i < round; i++) {
        StringUtil.getYearMonthDay(new Date());
    }
    long mid = System.currentTimeMillis();
    for (int i = 0; i < round; i++) {
        StringUtil.getYearMonthDay2(new Date());
    }
    long end = System.currentTimeMillis();
    System.out.println(mid - start);
    System.out.println(end - mid);
}

public static Date getYearMonthDay(Date date) throws ParseException {
    SimpleDateFormat f = new SimpleDateFormat("yyyyyMMdd");
    String dateStr = f.format(date);
    return f.parse(dateStr);
}

public static Date getYearMonthDay2(Date date) throws ParseException {
    Calendar c = Calendar.getInstance();
    c.setTime(date);
    c.set(Calendar.SECOND, 0);
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.HOUR_OF_DAY, 0);
    return c.getTime();
}
public static int compare(Date today, Date future, Date past) {
    Date today1 = StringUtil.getYearMonthDay2(today);
    Date future1 = StringUtil.getYearMonthDay2(future);
    Date past1 = StringUtil.getYearMonthDay2(past);
    return today.compare // or today.after or today.before
}

getYearMonthDay2(the calendar solution) is ten times faster. Now you have yyyy MM dd 00 00 00, and then compare using date.compare

Tiina
  • 4,285
  • 7
  • 44
  • 73