0
Calendar now = Calendar.getInstance();
System.out.println("Date and Time: "+now.get(Calendar.YEAR)+"-"
                    +now.get(Calendar.MONTH)+"-"
                    +now.get(Calendar.DAY_OF_MONTH)+" "
                    + now.get(Calendar.HOUR_OF_DAY)
                    + ":"
                    + now.get(Calendar.MINUTE));

It gives Output >>Date and Time : 2016-7-8 16:10

But I want >>Date and Time : 2016-8-8 16:10

Means it gives the day of month wrong,then how to rewrite above code for correct output.

Pornima Patil
  • 207
  • 1
  • 3
  • 14

1 Answers1

1

It's not giving wrong output. In java's Calendar, months are zero indexed.

see the documentation here.

MONTH

public static final int MONTH

Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.

It means they're starting from 0 to 11.

0 - January
1 - February
2 - March
3 - April
4 - May
5 - June
6 - July
7 - August
8 - September
9 - October
10 - November
11 - December

... and so on

You can simply add 1 and get the code working for you.

Raman Sahasi
  • 30,180
  • 9
  • 58
  • 71