get month of year from Calendar class of java - java

I wrote simple java program in which I get day of month, days in month and month
see below code :
//Calendar calendar = Calendar.getInstance();
Calendar calendar = new GregorianCalendar();
log.info("day of month: "+calendar.get(Calendar.DAY_OF_MONTH));
calendar.set(Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH);
log.info("days in month: "+calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
log.info("month: "+calendar.get(Calendar.MONTH));
Running above code I get this output:
day of month: 7
days in month: 31
month: 2
But when I put below statement
log.info("month: "+calendar.get(Calendar.MONTH));
before
log.info("day of month: "+calendar.get(Calendar.DAY_OF_MONTH));
I get this output: (which is what I want)
day of month: 7
days in month: 31
month: 5
Can any body help me understand why I get month: 2 ?

Youre setting the Calendar field to Calendar.MONTH (value 2) here
calendar.set(Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH);
^
You can do this
calendar.set(2014, Calendar.JUNE, 1);
although the Month 5 is June (since month field starts from 0 for Calendar) which only has 30 days

Look at the source code of Calendar.java of JDK.
public final static int MONTH = 2;
Here, Calendar.MONTH = 2, Calendar.YEAR=1 and Calendar.DAY_OF_MONTH = 5. You set these constant value to calender using set method like.
calendar.set(Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH);
| | |
1 2 5

tl;dr
LocalDate.now()
.getDayOfMonth()
…and…
YearMonth.from(
LocalDate.now()
).lengthOfMonth() // .getMonthValue() .getYear()
java.time
The modern approach uses the industry-leading java.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.
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 ) ;
Parts
Interrogate for the parts as needed.
int dayOfMonth = ld.getDayOfMonth() ;
int month = ld.getMonthValue() ;
int year = ld.getYear() ;
YearMonth
To work with the month as a whole, use YearMonth class.
YearMonth ym = YearMonth.from( ld ) ;
Ask for length of month.
int lengthOfMonth = ym.lengthOfMonth() ;
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

Java: Invalid week of year accepted

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.

Java Calendar get Xº day of the week of month

I'm need to do a method that returns the position of actual day in the next month.
for today (20/12/2016)
I need to call this method whit today date
The return given must to be (17/01/2016)
This method must return the third Tuesday of the next month
Is the 4 week of this month, but I need the Third Tuesday.
I try to use Calendar.MONTH, Calendar.WEEK_OF_MONTH, Calendar.DAY_OF_WEEK but I can't get the third, I always get the fourth.
Some thing like this:
public static Date getNextMonthDayOfWeel(Date d) {
Calendar c = Calendar.getInstance();
c.setTime(d);
int week = c.get(Calendar.WEEK_OF_MONTH);
int day = c.get(Calendar.DAY_OF_WEEK);
//// this block
if(!firstWeekOfMonthHad(day)){
week++;
}
//// this block
c.setFirstDayOfWeek(Calendar.SUNDAY);
c.add(Calendar.MONTH, 1);
c.set(Calendar.WEEK_OF_MONTH, week);
c.set(Calendar.DAY_OF_WEEK, day);
return c.getTime();
}
How can I get if the first week of the month have the specific day of the week?
If you use Java 8 or later, it is as simple as:
LocalDate.now()
.plusMonths(1)
.with(TemporalAdjusters.firstInMonth(DayOfWeek.TUESDAY))
.plusWeeks(3);
tl;dr
LocalDate.now( ZoneId.of( "Africa/Tunis" ) ) // Get current date in this particular time zone.
.plusMonths( 1 ) // Move to equivalent date in the month after.
.with(
TemporalAdjusters.dayOfWeekInMonth​( 3 , DayOfWeek.TUESDAY ) // Move to the ordinal number occurrence of a day-of-week within this month.
)
Details
You seem to be asking for the third Tuesday of next month.
The Answer by Mellgren is good, but here's a variation on that idea using a more appropriate TemporalAdjuster.
Avoid legacy classes
You are using troublesome old date-time classes that are now legacy, supplanted by the java.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.
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 );
Move to the next month.
LocalDate monthLater = today.plusMonths( 1 );
TemporalAdjuster
To move to the third Tuesday of the month, use an implementation of TemporalAdjuster found in the TemporalAdjusters class.
For an ordinal day-of-week within a month like “Third Tuesday of the month” or “First Thursday of the month”, Java offers a specific adjuster: TemporalAdjusters.dayOfWeekInMonth. Pass the ordinal number such as 3 for “third”, and a DayOfWeek enum object constant such as DayOfWeek.TUESDAY.
TemporalAdjuster ta = TemporalAdjusters.dayOfWeekInMonth( 3 , DayOfWeek.TUESDAY ); // Pass ordinal number and `DayOfWeek`.
LocalDate thirdTuesdayOfNextMonth = monthLater.with( ta );
Dump to console.
System.out.println( "today is " + today + " in zone " + z );
System.out.println( "Third Tuesday of next month is " + thirdTuesdayOfNextMonth );
See this code run live at IdeOne.com.
Today is 2018-01-20 in zone America/Montreal
Third Tuesday of next month is 2018-02-20
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 the date in java by setting DAY_OF_WEEK AND WEEK_OF_MONTH to calender class

i want to get the date after modifying the day of the week using Calender class in java
i want to print 16 7 2015(DD/MM/YYYY);
int monthIndex=6,weekIndex=2,dayIndex=4;
Calendar c = Calendar.getInstance();
c.set(Calendar.MONTH, (monthIndex + 1));
c.set(Calendar.WEEK_OF_MONTH, weekIndex+1 );
c.set(Calendar.DAY_OF_WEEK, dayIndex+1);
int recurMonth = c.get(Calendar.MONTH);
int recWeek=c.get(Calendar.WEEK_OF_MONTH);
int recurDate = c.get(Calendar.DATE);
int recurYear = c.get(Calendar.YEAR);
int dayofMonth=c.get(Calendar.DAY_OF_MONTH);
int dayofWeek=c.get(Calendar.DAY_OF_WEEK);
int dayofweekinmonth=c.get(Calendar.DAY_OF_WEEK_IN_MONTH);
but its showing wrong date
Its pretty clear, I guess.
Calendar today = Calendar.getInstance();
today.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
today.set(Calendar.WEEK_OF_MONTH, 5);
System.out.println(today.get(Calendar.DATE));
The code is self explanatory.
Format date using SimpleDateFormat:
public void printDate(int weekOfMonth, int dayOFWeek) {
Calendar calendar = Calendar.getInstance(Locale.US);
calendar.set(Calendar.WEEK_OF_MONTH, weekOfMonth);
calendar.set(Calendar.DAY_OF_WEEK, dayOFWeek);
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(df.format(calendar.getTime()));
}
tl;dr
To move to the following Monday:
LocalDate.of( 1986 , 2 , 23 ) // Represent a certain date, without time-of-day and without time zone.
.with( TemporalAdjusters.next( DayOfWeek.MONDAY ) ) // Move to the following Monday.
.format( // Generate a string representing this object’s value, using an automatically localizing formatter.
DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT ).withLocale( Locale.UK )
)
…or, for "third Monday in the same month":
LocalDate.of( 1986 , 2 , 23 ) // Represent a certain date, without time-of-day and without time zone.
.with( TemporalAdjusters.dayOfWeekInMonth( 3 , DayOfWeek.MONDAY ) ) // Move to the third Monday of the same month.
.format( // Generate a string representing this object’s value, using an automatically localizing formatter.
DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT ).withLocale( Locale.UK )
)
java.time
The modern approach uses the java.time classes that supplanted 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 ) ;
Adjusters
To move to another date, use a TemporalAdjuster implementation found in the TemporalAdjusters class. Specify the desired day-of-week using a DayOfWeek enum object.
LocalDate nextMonday = ld.with( TemporalAdjusters.next( DayOfWeek.MONDAY ) ) ;
If your goal is something like "move to the third Monday of the month", use another TemporalAdjuster implementation.
TemporalAdjuster ta = TemporalAdjusters.dayOfWeekInMonth( 3 , DayOfWeek.MONDAY ) ;
LocalDate thirdMondayOfSameMonth = ld.with( ta ) ;
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.
With a JDBC driver complying with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings or java.sql.* classes.
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.

Calendar Class problems

I am having problems with the Calendar Class.
Calendar cal = Calendar.getInstance ();
int iYear = cal.get (Calendar.YEAR); // get the current year
int iMonth = cal.get (Calendar.MONTH); // month...
int iDay = cal.get (Calendar.); // current day in the month
This... No Workie!! :-(
I used the debugger and found that the YEAR and the DAY_OF_MONTH are correct,
however, the MONTH is 1 (January) when it SHOULD BE 2 (February).
Here is where it gets even more WEIRD:
I then tried cal.clear ();
followed by cal.set (2014, 2, 27); // Today's Date - Feb 27, 2014
and the month was still 1 (i.e. January)
I set the date to days in January, (2014, 1, 1), (2014, 1, 16),etc
It correctly gave me a 1 for the month
After reading and trying many things (and pulling my hair out..)
I set it to a date in the future, my Birthday (2014, 5, 23) and other days.
For those dates, Month was correctly set to 5 (May)
Month in Calendar begins at 0, which means 0 is January, 1 is February, etc.
Java Date and Time API sucks. Use Joda-Time instead.
use constants in Calendar for month: Calendar.JANUARY etc
For example:
cal.set(2014, Calendar.FEBRUARY, 27);
Please see the description provided for MONTH Constant in Calendar Class.
Calendar.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.
So if you want to set the date in calendar than use below code snippet.
cal.set(2014, Calendar.FEBRUARY, 28);
I think it will help you.
tl;dr
LocalDate.now()
.getYear()
java.time
The modern approach uses the industry-leading java.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.
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 ) ;
Parts
Interrogate for the parts as needed.
int dayOfMonth = ld.getDayOfMonth() ;
int month = ld.getMonthValue() ;
int year = ld.getYear() ;
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.
Let try this simple program:
import java.util.Calendar;
class CalendarExample {
public static void main(String args[]) {
Calendar calendar = Calendar.getInstance();
System.out.println("Current Date : " + calendar.get(Calendar.DATE));
System.out.println("Current Month : " + calendar.get(Calendar.MONTH));
System.out.println("Current Year : " + calendar.get(Calendar.YEAR));
System.out.print("Current Time : ");
System.out.print(calendar.get(Calendar.HOUR) + ":");
System.out.print(calendar.get(Calendar.MINUTE) + ":");
System.out.print(calendar.get(Calendar.SECOND));
}
}
You get the o/p:
Current Date : 28
Current Month : 1
Current Year : 2014
Current Time : 11:18:3
In Calender class Jan as constant int is 0 , Feb is 1 ... .month constant int value is from 0,1,2..

Java - GregorianCalendar

I'm using the GregorianCalendar in Java, and I am wondering how I can use this to check whether or not a date is valid (E.g.: to check if Feb 29th is only in leap year, to check if the date is no sooner than the current data, etc).
I have created a GregorianCalendar object and passed it the values of the data I would like to check as follows:
GregorianCalendar cal1 = new GregorianCalendar(day,month,year);
If the date is valid, I'd like to return true. How could I do this?
Basic Idea: if you try to set the invalid date to Calendar instance, it would make it correct one,
For example if you set 45 as date it would not be the same once you set and retrieve
public boolean isValid(int d, int m, int y){
//since month is 0 based
m--;
//initilizes the calendar instance, by default the current date
Calendar cal = Calendar.getInstance();
//resetting the date to the one passed
cal.set(Calendar.YEAR, y);
cal.set(Calendar.MONTH, m);
cal.set(Calendar.DATE, d);
//now check if it is the same as we set then its valid, not otherwise
if(cal.get(Calendar.DATE)==d &&cal.get(Calendar.MONTH) ==m && cal.get(Calendar.YEAR) ==y){
return true;
}
//changed so not valid
return false;
}
Check that after creation, the day, month and year is still the same as the original values you passed. If the original values are incorrect, the date will get adjusted accordingly. E.g.. if you pass (29, 1, 2011) - note that the month value is 0-based so 1 is for February -, you will get back (1, 3, 2011).
tl;dr
java.time.LocalDate.of( 2018 , 2 , 31 )
➙ catch DateTimeException for invalid day-of-month number.
java.time
The GregorianCalendar class has been supplanted by the ZonedDateTime class as part of java.time built into Java 8 and later. A new method has been added to the old class for conversion.
ZonedDateTime zdt = myGregCal.toZonedDateTime() ;
You want a date-only value, so use LocalDate, without time-of-day and without time zone.
You can extract a LocalDate from a ZonedDateTime time.
LocalDate ld = zdt.toLocalDate() ;
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 ) ;
Valid value
to check if Feb 29th is only in leap year
The documentation for `LocalDate.of( year , month , day ) says:
The day must be valid for the year and month, otherwise an exception will be thrown.
So catch the DateTimeException.
try {
LocalDate ld = LocalDate.of( 2018 , 2 , 31 ) ; // Invalid, February never has 31 days.
return Boolean.TRUE ;
} catch ( DateTimeException e ) {
return Boolean.FALSE ;
}
Leap Year
Yes, LocalDate checks for Leap Year to handle February 29 correctly.
try {
LocalDate ld = LocalDate.of( 2018 , 2 , 29 ) ; // Invalid, as 2018 is a common year.
return Boolean.TRUE ;
} catch ( DateTimeException e ) {
return Boolean.FALSE ;
}
false
…
LocalDate ld = LocalDate.of( 2020 , 2 , 29 ) ; // Valid, as 2020 is a leap year.
…
true
Compare dates
to check if the date is no sooner than the current data
I assume you meant "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 ) ;
Compare with isBefore, isAfter, and isEqual.
boolean b = ld.isBefore( today ) ;
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.
Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.
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.

Categories

Resources