I just started going to university and basically just started using java and I want to know how to make a code that calculates the days between two dates but without the use of programs that take milliseconds and such things that I have seen in other answers.So this is the code I have created but it doesnt work perfectly it misses one day most of the times or something like that.Please I really need your help
Use a SimpleCalendar or GregorianCalendar classes...
but basing on what you posted, I'm unsure how to best suggest using those two... i'll draft a simple example shortly.
After some thought I'll just leave this here Difference in days between two dates in Java?
Taken from: http://www.staff.science.uu.nl/~gent0113/calendar/isocalendar_text5.htm
An approach could be to calculate the number of days from a fixed time for both dates and then just subtract those days. This will give you the difference of days between date 1 and date 2
The following method returns the number of days passed since 0 January 0 CE
public int calculateDate( int day, int month, int year) {
if (month < 3) {
year--;
month = month + 12;
}
return 365 * year + year/4 - year/100 + year/400 + ((month+1) * 306)/10 + (day - 62);
}
In you code now you should calculate the number of days since 0BC for both dates and then subtract them:
public void run() {
....
int dayDifference = calculateDate(day1, month1, year1) - calculateDate(day2, month2, year2);
....
}
tl;dr
java.time.temporal.ChronoUnit.DAYS.between(
LocalDate.of( 2012 , Month.MARCH , 23 ) ,
LocalDate.of( 2012 , Month.MAY , 17 )
)
55
java.time
The modern approach uses java.time classes that supplant the troublesome old legacy date-time classes.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.
LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ; // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.
Or, better, use the Month enum objects pre-defined, one for each month of the year. Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety.
LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;
ChronoUnit.DAYS
To get a count of days between two dates, call on the ChronoUnit enum object DAYS.
long days = ChronoUnit.DAYS.between( earlierLocalDate , laterLocalDate ) ;
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.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
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, 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.
Related
Postgresql returns day-of-week using EXTRACT with dow in the following fashion: 0 is Sunday, 1 is Monday, all the way to 6 which is Saturday, see official documentation.
I am looking for some official constants either in Java proper or in JDBC or perhaps some standard library (Apache Commons?) that match this numbering.
According to the same official documentation you should use isodow:
The day of the week as Monday (1) to Sunday (7)
tl;dr
I am looking for some official constants either in Java proper
Yes, Java defines the seven day-of-week values in the DayOfWeek enum using the same standard ISO 8601 definition as the isodow function in Postgres where a week runs from Monday-Sunday with days numbered 1-7.
DayOfWeek.WEDNESDAY.getValue() // Returns an `int` 1-7 for Monday-Sunday.
3
java.time.DayOfWeek enum
As the Answer by Rcordoval suggests, use the Postgres function isodow.
The “iso” in isodow refers to ISO 8601 standard and its definition of week where days are numbered 1-7 for Monday-Sunday.
Java supports that same definition of week in its DayOfWeek enum. That class defines seven objects for you, one for each day of the week such as DayOfWeek.MONDAY. To get each object’s day-of-week number, 1-7 for Monday-Sunday, call DayOfWeek::getValue. But in your Java coding, focus on using and passing around the DayOfWeek objects themselves rather than mere integer numbers.
int dowNumber = DayOfWeek.WEDNESDAY.getValue() ;
3
Going from the integer number to a DayOfWeek object is bit trickier, as we need to access a Java array using an index. The index means zero-based counting, so subtract one from your day-of-week number. Wednesday is day # 3, so subtract 1 for a result of 2 to access DayOfWeek.WEDNESDAY.
DayOfWeek dow = DayOfWeek.values()[ 3-1 ] ; // Get object named `WEDNESDAY` using zero-based index counting, so 3 - 1 = 2.
dow.toString(): WEDNESDAY
By the way, to automatically localize the name of the day-of-week, call DayOfWeek::getDisplayName.
Java rather than SQL
I am currently writing a query that is finding customers that currently have a Friday 10:00 AM in their respective time zone, so I need to pass in the concept of "Friday" into the query and of course I don't want to hard-code it.
May be better to do this work in Java using the industry-leading java.time classes rather than in SQL.
You must be very careful about time zones. Be explicit with time zones rather than relying on implicit default zones.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
Next, get the following Friday, or stick with today if it is already a Friday. Use a TemporalAdjuster to adjust between dates, specifically the one found in TemporalAdjusters.
LocalDate nextOrSameFriday = today.with( TemporalAdjusters.nextOrSame( DayOfWeek.FRIDAY ) ) ;
You said you were aiming at 10 AM.
LocalTime lt = LocalTime.of( 10 , 0 ) ; // 10 AM.
Combine with date and zone to get a specific moment.
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
Adjust into UTC by extracting a Instant object. Same moment, same point on the timeline, but different wall-clock time.
Instant instant = zdt.toInstant() ;
Formulate your SQL to query your database column of type TIMESTAMP WITH TIME ZONE.
String sql = "SELECT * from tbl WHERE when_col = ? ; " ;
…
myPreparedStatement.setObject( … , instant ) ;
And retrieval.
Instant instant = myResultSet.getObject( … , Instant.class ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
In this approach you have need for the dow or isodow functions in Postgres.
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, and later
Built-in.
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.
You can use the Calendar constants minus 1 so you can match the PostgreSQL values ie: Calendar.SUNDAY = 1
I have written the following Java code to get a the first day of a week of year.
Calendar cal = Calendar.getInstance(Locale.GERMAN);
cal.clear();
cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, Calendar.MONDAY);
cal.set(Calendar.YEAR, 2016);
cal.set(Calendar.WEEK_OF_YEAR, weekNumber);
DateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
System.out.println( sdf.format(cal.getTime()) );
By using the input week of year 53 it should result into an error acutally because this week of year does not exist in 2016. Instead it shows me the next possible first date from next year.
Is there a neat way to correct my code or do I have to check the input week of year by myself?
Thanks for your help.
tl;dr
If you mean a standard ISO 8601 week, use the YearWeek class from the ThreeTen-Extra library.
For specific week number in specific week-based year:
YearWeek.of( // Standard ISO 8601 week, where week # 1 has the first Thursday of the calendar year, and runs Monday-Sunday.
2018 , // Week-based year, NOT calendar year.
37 // Week-of-week-based-year. Runs 1-52 or 1-53.
)
.atDay( DayOfWeek.MONDAY ) // Returns a `LocalDate` object.
➡ Trap for java.time.DateTimeException if the input is not valid, if there is no such week in that week-based-year.
For current week:
YearWeek.now( // Standard ISO 8601 week, where week # 1 has the first Thursday of the calendar year, and runs Monday-Sunday.
ZoneId.of( "Pacific/Auckland" ) // Determining a week means determining a date, and that requires a time zone. For any given moment, the date varies around the globe by zone.
)
.atDay( DayOfWeek.MONDAY ) // Returns a `LocalDate` object.
Define “week”
Define what you mean by “week”. Is week # 1 the one with January 1st? Is week # 1 the first to have all seven days composed of days in the new year? If so, what is the first-last days of the week, Sunday-Saturday or Monday-Sunday or something else? Or is week # 1 the first to have a certain day of the week?
The troublesome old date-time classes defined a week by depending on Locale. If you fail to specify a Locale, the JVM’s current default Locale is silently implicitly applied. So your results can vary at runtime.
If possible I recommend using the standard ISO 8601 week definition. The week runs from Monday-Sunday, and week # 1 contains the first Thursday of the calendar year. So there are either 52 or 53 weeks per year.
Getting the current week means getting the current date. A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
If you simply want a certain day-of-week on or before that date, then never mind about the week. Use a TemporalAdjuster implementation found in TemporalAjdusters. Specify your day-of-week via the DayOfWeek enum.
LocalDate mondayOnOrBeforeToday = today.with( TemporalAdjusters.previousOrSame( DayOfWeek.MONDAY ) ) ;
ThreeTen-Extra library
If you do want to work with ISO 8601 weeks, there is limited support available in the IsoFields class. But I recommend instead that you add the ThreeTen-Extra library to your project. That library provides additional date-time classes that complement those built into Java SE 8 and later. In particular, you get the YearWeek class.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
YearWeek yw = YearWeek.now( z ) ;
Ask for the LocalDate of a day-of-week in that week.
LocalDate ld = yw.atDay( DayOfWeek.MONDAY ) ;
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, and later
Built-in.
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.
So I want to do something with Java GregorianCalendar that seems to be going way harder than it should. I want to get the day of the week from the month and date. But it won't do that. I know that people often get the wrong answer to this because they don't know month is numbered from 0 while DAY_OF_WEEK is numbered from 1 (like here and here). But that's not my problem. My problem is that DAY_OF_WEEK always, always, returns 7, no matter what I set the date to. When I convert the GregorianCalendar to string, DAY_OF_WEEK appears as ?, even though I have set year, month, and dayOfMonth.
The code where this is happening:
GregorianCalendar theDate;
public ObservableDate(int year, int month, int dayOfMonth, int hourOfDay, int minute, int second)
{
theDate = new GregorianCalendar(year, month, dayOfMonth, hourOfDay, minute, second);
theDate.setFirstDayOfWeek(GregorianCalendar.SUNDAY);
System.out.println("DAY_OF_WEEK = "+theDate.DAY_OF_WEEK);
System.out.println(theDate.toString());
}
The code that calls it:
ObservableDate theDate = new ObservableDate(2001, 3, 24, 9, 00, 00);
Output:
DAY_OF_WEEK = 7
java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=false,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/New_York",offset=-18000000,dstSavings=3600000,useDaylight=true,transitions=235,lastRule=java.util.SimpleTimeZone[id=America/New_York,offset=-18000000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=?,YEAR=2001,MONTH=3,WEEK_OF_YEAR=?,WEEK_OF_MONTH=?,DAY_OF_MONTH=24,DAY_OF_YEAR=?,DAY_OF_WEEK=?,DAY_OF_WEEK_IN_MONTH=?,AM_PM=0,HOUR=9,HOUR_OF_DAY=9,MINUTE=0,SECOND=0,MILLISECOND=?,ZONE_OFFSET=?,DST_OFFSET=?]
Any idea why this is happening?
You are accessing the field constant instead of getting its' value. I believe you wanted to use something like,
System.out.println("DAY_OF_WEEK = " + theDate.get(Calendar.DAY_OF_WEEK));
Your problem is you're accessing the constant DAY_OF_WEEK in the Calendar class (Calendar.DAY_OF_WEEK).
To properly get the day of week use the theDate variable's .get() method like so:
theDate.get(Calendar.DAY_OF_WEEK);
tl;dr
For a smart DayOfWeek enum object.
ZonedDateTime.of( 2001 , 3 , 24 , 9 , 0 , 0 , 0 , ZoneId.of( "Pacific/Auckland" ) ) // Moment as seen by people in a certain region (time zone).
.getDayOfWeek() // Extract a `DayOfWeek` enum object to represent that day-of-week of that moment.
For a mere integer 1-7 for Monday-Sunday.
ZonedDateTime.of( 2001 , 3 , 24 , 9 , 0 , 0 , 0 , ZoneId.of( "Pacific/Auckland" ) )
.getDayOfWeek()
.getValue() // Translate that `DayOfWeek` object into a mere integer 1-7 for Monday-Sunday.
java.time
The modern approach uses the java.time classes that supplant the troublesome old legacy date-time classes. Calendar is replaced by ZonedDateTime.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ZonedDateTime.of( 2001 , 3 , 24 , 9 , 0 , 0 , 0 , z );
The DayOfWeek enum defines seven objects for each day of the week.
DayOfWeek dow = zdt.getDayOfWeek() ; // Get `DayOfWeek` enum object representing this moment’s day-of-week.
You can ask the DayOfWeek to localize the name of the day.
I suggest using these DayOfWeek objects across your codebase rather than mere integer numbers. But if you insist, you can get a number. Unlike in GregorianCalendar the numbers have a fixed meaning and do not vary by locale. The meaning is 1-7 for Monday-Sunday, per the ISO 8601 standard.
int dowNumber = zdt.getDayOfWeek().getValue() ; // 1-7 for Monday-Sunday per ISO 8601.
Immutable object
Note that java.time uses immutable objects. Rather than alter member variables on the object (“mutate”), calls to adjust the value results in a new object, leaving the original object unchanged.
ZonedDateTime zdtTomorrow = zdt.now( z ).plusDays( 1 ) ; // Alterations result in a new object, leaving original intact. Known as *immutable objects*.
Time zone
You failed to specify a time zone in your constructor’s arguments and in the arguments passed to new GregorianCalendar. In such cases, the JVM’s current default time zone is implicitly assigned. That default can vary by machine, and can even change at any moment during runtime. Better to specify your desired/expected time zone.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
Octal number literals
Beware of your 00 literal value. A leading zero means octal base-8 number rather than decimal number in Java source code. You lucked-out as octal zero is also decimal zero.
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.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
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, 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.
How to get Unix timestamp value only for particular year.
I have a situation where in server side for DOB i store only year. So in android i take Age value and then subtract current year with the age and send that year to server. To send that year i need to convert to Unix timestamp because in server side it stores in Unix timestamp format.
Somebody please help what can be done. I saw some links which uses getTime() and divide it by 1000. But that would be whole year with date and month.
Try this:
Calendar myCal = Calendar.getInstance();
myCal.set(Calendar.YEAR, theYear); // Set the year you want
myCal.set(Calendar.DAY_OF_YEAR, 1);
myCal.set(Calendar.HOUR, 0);
myCal.set(Calendar.MINUTE, 0);
Date theDate = myCal.getTime();
java.time
I get current year and i am converting it to integer and then age which user enters. For example, current year is 2014 and he puts age as 20 so his dob year is 1994. I wanted timestamp value of 1994. And i wanted in GMT.
Apparently you want to the moments at each end of a year.
The modern solution uses the java.time classes that supplanted the terrible old legacy date-time classes.
Parse integer from string
First the year.
String input = "20" ;
integer age = Integer.parseInt( input ) ;
Time zone
Determining a date, and therefore a year, requires a time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your [desired/expected time zone][2] explicitly as an argument.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
Year
Get the current year.
Year currentYear = Year.now( z ) ;
LocalDate & ZonedDateTime
Get the first day of the year as a LocalDate. From that, get the first moment of the day as a ZonedDateTime. A day does not always start at 00:00, so let java.time determine the first moment.
LocalDate firstOfYear = currentYear.atDay( 1 ) ;
ZonedDateTime yearStart = firstOfYear.atStartOfDay( z ) ;
Half-Open
Use Half-Open approach to defining a span-of-time, where beginning is inclusive while the ending is exclusive.
LocalDate firstOfFollowingYear = currentYear.plusYears( 1 ).atDay( 1 ) ;
ZonedDateTime yearStop = firstOfFollowingYear.atStartOfDay( z ) ;
Count-from-epoch
You do not specify what you mean exactly by “Unix timestamp”. I will guess you mean a count of whole seconds since the epoch reference of first moment of 1970 in UTC.
long start = yearStart.toEpochSecond() ;
long stop = yearStop.toEpochSecond() ;
For more discussion, see my Answer to a similar Question.
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
Most 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.
This question already has answers here:
Why is January month 0 in Java Calendar?
(18 answers)
Closed 2 years ago.
Calendar rightNow = Calendar.getInstance();
String month = String.valueOf(rightNow.get(Calendar.MONTH));
After the execution of the above snippet, month gets a value of 10 instead of 11. How come?
Months are indexed from 0 not 1 so 10 is November and 11 will be December.
They start from 0 - check the docs
As is clear by the many answers: the month starts with 0.
Here's a tip: you should be using SimpleDateFormat to get the String-representation of the month:
Calendar rightNow = Calendar.getInstance();
java.text.SimpleDateFormat df1 = new java.text.SimpleDateFormat("MM");
java.text.SimpleDateFormat df2 = new java.text.SimpleDateFormat("MMM");
java.text.SimpleDateFormat df3 = new java.text.SimpleDateFormat("MMMM");
System.out.println(df1.format(rightNow.getTime()));
System.out.println(df2.format(rightNow.getTime()));
System.out.println(df3.format(rightNow.getTime()));
Output:
11
Nov
November
Note: the output may vary, it is Locale-specific.
As several people have pointed out, months returned by the Calendar and Date classes in Java are indexed from 0 instead of 1. So 0 is January, and the current month, November, is 10.
You might wonder why this is the case. The origins lie with the POSIX standard functions ctime, gmtime and localtime, which accept or return a time_t structure with the following fields (from man 3 ctime):
int tm_mday; /* day of month (1 - 31) */
int tm_mon; /* month of year (0 - 11) */
int tm_year; /* year - 1900 */
This API was copied pretty much exactly into the Java Date class in Java 1.0, and from there mostly intact into the Calendar class in Java 1.1. Sun fixed the most glaring problem when they introduced Calendar – the fact that the year 2001 in the Gregorian calendar was represented by the value 101 in their Date class. But I'm not sure why they didn't change the day and month values to at least both be consistent in their indexing, either from zero or one. This inconsistency and related confusion still exists in Java (and C) to this day.
Months start from zero, like indexes for lists.
Therefore Jan = 0, Feb = 1, etc.
From the API:
The first month of the year is JANUARY
which is 0; the last depends on the
number of months in a year.
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Calendar.html
tl;dr
LocalDate.now() // Returns a date-only `LocalDate` object for the current month of the JVM’s current default time zone.
.getMonthValue() // Returns 1-12 for January-December.
Details
Other answers are correct but outdated.
The troublesome old date-time classes had many poor design choices and flaws. One was the zero-based counting of month numbers 0-11 rather than the obvious 1-12.
java.time
The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
Now in maintenance mode, the Joda-Time project also advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time.
Months 1-12
In java.time the month number is indeed the expected 1-12 for January-December.
The LocalDate class represents a date-only value without time-of-day and without time zone.
Time zone
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) );
int month = today.getMonthValue(); // Returns 1-12 as values.
If you want a date-time for a time zone, use ZonedDateTime object in the same way.
ZonedDateTime now = ZonedDateTime.now( ZoneId.of( "America/Montreal" ) );
int month = now.getMonthValue(); // Returns 1-12 as values.
Convert legacy classes
If you have a GregorianCalendar object in hand, convert to ZonedDateTime using new toZonedDateTime method added to the old class. For more conversion info, see Convert java.util.Date to what “java.time” type?
ZonedDateTime zdt = myGregorianCalendar.toZonedDateTime();
int month = zdt.getMonthValue(); // Returns 1-12 as values.
Month enum
The java.time classes include the handy Month enum, by the way. Use instances of this class in your code rather than mere integers to make your code more self-documenting, provide type-safety, and ensure valid values.
Month month = today.getMonth(); // Returns an instant of `Month` rather than integer.
The Month enum offers useful methods such as generating a String with the localized name of the month.
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.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
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
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
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.
cal.get(Calendar.MONTH) + 1;
The above statement gives the exact number of the month. As get(Calendar.Month) returns month starting from 0, adding 1 to the result would give the correct output. And keep in mind to subtract 1 when setting the month.
cal.set(Calendar.MONTH, (8 - 1));
Or use the constant variables provided.
cal.set(Calendar.MONTH, Calendar.AUGUST);
It would be better to use
Calendar.JANUARY
which is zero ...