Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment in month value in Date class in Java

Tags:

java

date

So, I'm typing a very simple program to accept the date from the user and print it back to them. On my first attempt, i saw that the year gets incremented by 1900. What exactly is the reason? I also see that the month value is being incremented by one. Here is the program block

Date dateInput = new Date(114,2,20,13,18,48); //2014-1900 = 114
System.out.println("Date Entered by You : ");
System.out.println(dateInput);

The output for this is

Date Entered by You : 
Thu Mar 20 13:18:48 IST 2014

I entered the month value as 2, but it it printing at as March. What could be the problem? And why is the Date class preprogrammed to add a 1900 to the entered year?

like image 345
woodhead92 Avatar asked May 15 '26 16:05

woodhead92


2 Answers

Check the Date API

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


I entered the month value as 2, but it it printing at as March. What could be the problem?

So as per api, in your case, it's March.

On my first attempt, i saw that the year gets incremented by 1900. What exactly is the reason?

You have used depreciated Date(int year, int month, int date, int hrs, int min, int sec) Constructor, and it's says

As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date, hrs, min, sec) or GregorianCalendar(year + 1900, month, date, hrs, min, sec). Allocates a Date object and initializes it so that it represents the instant at the start of the second specified by the year, month, date, hrs, min, and sec arguments, in the local time zone.


And, It's just part of the horrendous mess which is the Java date/time API. Month starts with zero, but, day starts with 1. In Java 8, the new java.time.* package (defined by JSR-310 and inspired by Joda-Time) fixes this problem and more.

like image 140
Abimaran Kugathasan Avatar answered May 17 '26 05:05

Abimaran Kugathasan


The month index start from 0-January 1 febuary ans so on 11 for december

like image 38
Chirag Sutariya Avatar answered May 17 '26 05:05

Chirag Sutariya