tl;dr
holidays.add(
new Holiday(
LocalDate.of( 2018 , Month.MAY , 8 ) ,
"National Coconut Cream Pie Day"
)
)
java.time
This work is so much simpler with the modern java.time classes rather than obsolete legacy Calendar
class and its commonly-used subclass, GregorianCalendar
.
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 ) ;
Custom class
You misused the name Holidays
twice in your code, once as the name of the list collection and once as the name of the individual "holiday" class/object. Furthermore, the first used as holding a static class variable, not likely a good design.
I will assume the second is a typo, and the second should be Holiday
as the name of the class representing a particular holiday on a particular date.
Your Holiday
class would look something like this.
class Holiday
{
private LocalDate localDate;
private String name;
private DayOfWeek dow;
public Holiday ( LocalDate localDateArg , String nameArg )
{
this.localDate = localDateArg;
this.name = nameArg;
}
public LocalDate getLocalDate ( )
{
return localDate;
}
public String getName ( )
{
return name;
}
// With arguments.
public String format ( Locale locale , FormatStyle style )
{
String date = this.localDate.format( DateTimeFormatter.ofLocalizedDate( style ).withLocale( locale ) );
String output = date + " | " + this.name;
return output;
}
@Override
public String toString ( )
{
return "Holiday{ " +
"localDate=" + localDate +
", name='" + name + '\'' +
" }";
}
}
Next, we use that class.
List
Instantiate an empty List
. You can optionally set the initial capacity of the ArrayList
.
List < Holiday > holidays = new ArrayList <>( 3 );
Populate that list.
holidays.add( new Holiday( LocalDate.of( 2018 , Month.MAY , 8 ) , "National Coconut Cream Pie Day" ) );
holidays.add( new Holiday( LocalDate.of( 2018 , Month.AUGUST , 9 ) , "National Rice Pudding Day" ) );
holidays.add( new Holiday( LocalDate.of( 2018 , Month.JANUARY , 5 ) , "National Whipped Cream Day" ) );
holidays.toString():
[Holiday{ localDate=2018-05-08, name='National Coconut Cream Pie Day' }, Holiday{ localDate=2018-08-09, name='National Rice Pudding Day' }, Holiday{ localDate=2018-01-05, name='National Whipped Cream Day' }]
Sort with Comparator
To sort, pass an implementation of Comparator
. Here is the classic Java syntax.
holidays.sort( new Comparator < Holiday >()
{
@Override
public int compare ( Holiday o1 , Holiday o2 )
{
int c = o1.getLocalDate().compareTo( o2.getLocalDate() );
return c;
}
} );
Here is that same Comparator
in modern Java syntax using a lambda.
holidays.sort( ( o1 , o2 ) ->
{
int c = o1.getLocalDate().compareTo( o2.getLocalDate() );
return c;
} );
Or even shorter lambda syntax, but not necessarily better.
holidays.sort( ( o1 , o2 ) -> o1.getLocalDate().compareTo( o2.getLocalDate() ) );
Either way, the results are:
holidays.toString():
[Holiday{ localDate=2018-01-05, name='National Whipped Cream Day' }, Holiday{ localDate=2018-05-08, name='National Coconut Cream Pie Day' }, Holiday{ localDate=2018-08-09, name='National Rice Pudding Day' }]
Formatting output
For your date with day-of-week, use the format
method we defined that automatically localized to the human language and cultural norms we specify with a Locale
and FormatStyle
.
for ( Holiday holiday : holidays )
{
System.out.println( holiday.format( Locale.CANADA_FRENCH , FormatStyle.FULL ) );
}
vendredi 5 janvier 2018 | National Whipped Cream Day
mardi 8 mai 2018 | National Coconut Cream Pie Day
jeudi 9 août 2018 | National Rice Pudding Day
Or in US English, passing Locale.US
:
Friday, January 5, 2018 | National Whipped Cream Day
Tuesday, May 8, 2018 | National Coconut Cream Pie Day
Thursday, August 9, 2018 | National Rice Pudding Day
Note that you can get a DayOfWeek
enum object from LocalDate
. From that you can automatically localize the name of that day with the DayOfWeek::getDisplayName
method.
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?
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.util.Date
,java.util.Calendar
, andjava.text.SimpleDateFormat
are now legacy, supplanted by the java.time classes. Much of the java.time functionality is back-ported to Java 6 & Java 7 in the ThreeTen-Backport project. Further adapted for earlier Android in the ThreeTenABP project. See How to use ThreeTenABP…. – Basil Bourque