1

I am trying to take a variable of Date type . But output I am getting is automatically getting incremented by one month. Here is what I am doing

Date d1 = new Date(2020,8,15);
System.out.println(d1);

d1's value is coming 2020-09-15 instead of 2020-08-15.

RS0023
  • 35
  • 6
  • 1
    Yes we have to write 8 instead of 08, I have edited the code in the question. – RS0023 Aug 13 '20 at 12:46
  • I recommend you don’t use `Date`. That class is poorly designed and long outdated. Instead use `LocalDate` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). If you necessarily need a `Date`, create as `Date.from(LocalDate.of(2020, Month.AUGUST, 15).atZone(ZoneId.systemDefault()).toInstant())`. Under no circumstances use the 3-arg `Date` constructor. It has been deprecated since early 1997. – Ole V.V. Aug 13 '20 at 15:05
  • Or if you need a `java.sql.Date` — you probably don’t, you can transfer the `LocalDate` to your SQL database, see [Insert & fetch java.time.LocalDate objects to/from an SQL database such as H2](https://stackoverflow.com/questions/43039614/insert-fetch-java-time-localdate-objects-to-from-an-sql-database-such-as-h2). – Ole V.V. Aug 13 '20 at 15:08
  • For now my issue was solved. But as you said it will be a better approach to use LocalDate. I will use it further instead of using Date. Thanks – RS0023 Aug 13 '20 at 15:11

2 Answers2

1

Unfortunately, month values are starting at 0, which makes an 8 be September when using the outdated API (e.g. java.util.Date).

That means to get the desired output, you would have to write (without a leading zero)

Date d1 = new Date(2020, 9, 15);
System.out.println(d1);

Fortunately, there's java.time now!

You can use it like this

public static void main(String[] args) {
    LocalDate d1 = LocalDate.of(2020, 8, 15);
    System.out.println(d1);
}

and it outputs

2020-08-15
deHaar
  • 11,298
  • 10
  • 32
  • 38
0

Date takes months from 0 to 11 and not 1 to 12. So, new Date(2020,08,15); is actually 15th September 2020

And when date is printed/formatted, actual month is printed (values 1 to 12). According to docs

A month is represented by an integer from 0 to 11; 0 is January, 1 is February, and so forth; thus 11 is December.

Note : Always prefer java.time API over java.util.Date

Smile
  • 3,072
  • 1
  • 19
  • 31