LocalDate Java Class
LocalDate Java class is an immutable and thread-safe class introduced in new Date and Time API in Java8 and date is represented in format YYYY-MM-dd.
All classes of Java8 Date/Time API are located in java.time package and today we are going to look at one of the classes from this package that is LocalDate.
LocalDate Structure
1
2
3
| public final class LocalDate
extends Object
implements Temporal, TemporalAdjuster, ChronoLocalDate, Serializable
|
As we can see LocalDate is a final class and also immutable so we cannot inherit it and it implements interfaces Temporal, TemporalAdjuster, ChronoLocalDate, Serializable
Introduction about the LocalDate Java class
LocalDate class is immutable and thread-safe.
This is a value-based class thus use of equals method is recommended for comparisons.
LocalDate provides date format as YYYY-MM-dd.
The LocalDate class does not have time or timezone data, So LocalDate is preferable for Birthday, National Holiday representation.
Now we will see how we can use LocalDate
Importing LocalDate Class
Java LocalDate class is in java.time package. Here what it looks like :
1
| import java.time.LocalDate;
|
Creating New LocalDate Instance
- Using LocalDate now() method to get the current date.
1
2
3
| // To get current date
LocalDate todaysDate = LocalDate.now();
System.out.println(todaysDate); // 2020-06-21
|
- Using LocalDate of() method to get the specified date in of method parameter.
1
2
3
4
5
6
7
| // To get Specified date
LocalDate twentyFirstJune2019= LocalDate.of(2019, Month.JUNE, 21);
System.out.println(twentyFirstJune2019); //2019-06-21
// months values start at 1
LocalDate firstAug2014 = LocalDate.of(2014, 8, 1);
System.out.println(firstAug2014); // 2014-08-01
|
- Using LocalDate parse() method to get specified date passing a parameter as a string with format YYYY-MM-dd
1
2
3
4
| //Using parse method with string as input,
//Obtains an instance of LocalDate from a text string such as 2007-12-03.
LocalDate dateUsingParseMethod = LocalDate.parse("2020-06-21");
System.out.println(dateUsingParseMethod);//2020-06-21
|
- Using LocalDate ofYearDay() method to get specified date passing a Year and day of the year
1
2
3
| // the 215th day of 2018
LocalDate day_215_of_2018 = LocalDate.ofYearDay(2018, 215);
System.out.println(day_215_of_2018); // 2018-08-03
|
Getting Date Information
LocalDate Java class has lots of other useful methods to get details about date, for example, year, month, day of the year, day of the month, day of the week, the month of the year, length of the month, length of the year, leap year or not, etc. Below are a few examples
- getDayOfMonth() to get day of month.
1
2
3
| // Get day of the month
int dayOfTheMonth = odaysDate.getDayOfMonth();
System.out.println(dayOfTheMonth); // 21
|
- getDayOfWeek() to get the day of the week.
1
2
3
| // Get day of the Week
DayOfWeek dayOfTheWeek = todaysDate.getDayOfWeek();
System.out.println(dayOfTheWeek); // SUNDAY
|
- getDayOfYear() to get the day of the year.
1
2
3
| // Get day of the Year
int dayOfTheYear = todaysDate.getDayOfYear();
System.out.println(dayOfTheYear); // 173
|
- getMonth() to get month name.
1
2
3
| // Gets the month-of-year field using the Month enum.
Month month = todaysDate.getMonth();
System.out.println(month); // JUNE
|
- getMonthValue() to get the month of the year from 1 to 12.
1
2
3
| // Gets the month-of-year field from 1 to 12.
int monthValue = todaysDate.getMonthValue();
System.out.println(monthValue);// 6
|
- getYear() to get year value.
1
2
3
| // Gets the year value.
int year = todaysDate.getYear();
System.out.println(year); // 2020
|
- isLeapYear() to check year is a leap year or not.
1
2
3
| // Checks if the year is a leap year
boolean isLeapYear = todaysDate.isLeapYear();
System.out.println(isLeapYear); // true
|
- lengthOfMonth() to check the length of the month.
1
2
3
| // Returns the length of the month represented by this date.
int lengthOfMonth = todaysDate.lengthOfMonth();
System.out.println(lengthOfMonth);// 30
|
- lengthOfYear() to check the length of the year.
1
2
3
| // Returns the length of the year represented by this date.
int lengthOfYear = todaysDate.lengthOfYear();
System.out.println(lengthOfYear); // 366
|
LocalDate Minus Methods
LocalDate Minus Methods are used to get a past date using minus days, months, weeks, years methods.
- minus() method with ChronoUnit Field Specified returns a copy of this date with the specified amount subtracted.
1
2
3
4
5
6
7
8
9
| // Returns a copy of this date with the specified amount subtracted.
// with respect to Chronounit specified
// Give date with 4 days before todaysDate //here todayDate is 2020-06-21
LocalDate newDate = todaysDate.minus(4, ChronoUnit.DAYS);
System.out.println(newDate); // 2020-06-17
// Give date with 4 month before date specified here todayDate is 2020-06-21
LocalDate newDateBefore4Month = todaysDate.minus(4, ChronoUnit.MONTHS);
System.out.println(newDateBefore4Month); // 2020-02-21
|
- minusDays() method returns a copy of this LocalDate with the specified number of days subtracted.
1
2
3
| // Specific method to minusDays from specified date here todayDate is 2020-06-21
LocalDate minusDays = todaysDate.minusDays(4);
System.out.println(minusDays); // 2020-06-17
|
- minusWeeks() method returns a copy of this LocalDate with the specified number of weeks subtracted.
1
2
3
| // Specific method to minusWeeks here todayDate is 2020-06-21
LocalDate minusWeeks = todaysDate.minusWeeks(4);
System.out.println(minusWeeks); // 2020-05-24
|
- minusMonths() method returns a copy of this LocalDate with the specified number of months subtracted.
1
2
3
| // Specific method to minusMonths here todayDate is 2020-06-21
LocalDate minusMonths = todaysDate.minusMonths(4);
System.out.println(minusMonths); // 2020-02-21
|
- minusYears() method returns a copy of this LocalDate with the specified number of years subtracted.
1
2
3
| // Specific method to minusYears here todayDate is 2020-06-21
LocalDate minusYears = todaysDate.minusYears(4);
System.out.println(minusYears); // 2016-06-21
|
LocalDate Plus methods
LocalDate Plus methods are used to get future date using plus days, months, weeks, years methods.
- plus() method with ChronoUnit Field Specified returns a copy of this date with the specified amount added.
1
2
3
4
5
6
7
8
9
| // Returns a copy of this date with the specified amount added.
// with respect to Chronounit specified
// Give date with 4 days after todaysDate //here todayDate is 2020-06-21
LocalDate dateAfter4daysAdded = todaysDate.plus(4, ChronoUnit.DAYS);
System.out.println(dateAfter4daysAdded); // 2020-06-25
// Give date with 4 year after todaysDate //here todayDate is 2020-06-21
LocalDate newDateAfter4Year = todaysDate.plus(4, ChronoUnit.YEARS);
System.out.println(newDateAfter4Year); // 2024-06-21
|
- plusDays() method returns a copy of this LocalDate with the specified number of days added.
1
2
3
| // Specific method to plusDays here todayDate is 2020-06-21
LocalDate plusDays = todaysDate.plusDays(4);
System.out.println(plusDays); // 2020-06-25
|
- plusWeeks() method returns a copy of this LocalDate with the specified number of weeks added.
1
2
3
| // Specific method to plusWeeks here todayDate is 2020-06-21
LocalDate plusWeeks = todaysDate.plusWeeks(4);
System.out.println(plusWeeks); // 2020-07-19
|
- plusMonths() method returns a copy of this LocalDate with the specified number of months added.
1
2
3
| // Specific method to plusMonths here todayDate is 2020-06-21
LocalDate plusMonths = todaysDate.plusMonths(4);
System.out.println(plusMonths); // 2020-10-21
|
- plusYears() method returns a copy of this LocalDate with the specified number of years added.
1
2
3
| // Specific method to plusYears here todayDate is 2020-06-21
LocalDate plusYears = todaysDate.plusYears(4);
System.out.println(plusYears); // 2024-06-21
|
LocalDate with Methods
with methods are method provided by LocalDate class to alter date according to dayValueOfMonth, dayValueOfYear, monthvalue, yearValue and get LocalDate altered value.
- with() method returns a copy of this date with the specified field set to a new value.
1
2
3
| // Returns a copy of this date with the specified field set to a new value.
LocalDate withDayOfMonthSpecified = todaysDate.with(ChronoField.DAY_OF_MONTH, 12);
System.out.println(withDayOfMonthSpecified); // 2020-06-12
|
- withDayOfMonth() method returns a copy of this LocalDate with the day-of-month altered.
1
2
3
| // Returns a copy of this LocalDate with the day-of-month altered.
LocalDate withDayOfMonth = todaysDate.withDayOfMonth(1);
System.out.println(withDayOfMonth); // 2020-06-01
|
- withDayOfYear() method returns a copy of this LocalDate with the day-of-year altered.
1
2
3
| // Returns a copy of this LocalDate with the day-of-year altered.
LocalDate withDayOfYear = todaysDate.withDayOfYear(300);
System.out.println(withDayOfYear); // 2020-10-26
|
- withMonth() method returns a copy of this LocalDate with the month-of-year altered.
1
2
3
| // Returns a copy of this LocalDate with the month-of-year altered.
LocalDate withMonthOfYear = todaysDate.withMonth(3);
System.out.println(withMonthOfYear); // 2020-03-21
|
- withYear() method returns a copy of this LocalDate with the year altered.
1
2
3
| // Returns a copy of this LocalDate with the year altered.
LocalDate withYear = todaysDate.withYear(1992);
System.out.println(withYear); // 1992-06-21
|
Java LocalDate to Date
As we are migrating our projects to Java8 we generally encounter a situation where we still need to change LocalDate to Legacy Date Object so that is also one of the things that developer faces Here is the example to convert localdate to date object
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
public class LocalDateToDate {
public static void main(String[] args) {
LocalDate todaysDate = LocalDate.now();
// Using Date from method to convert LocalDate to date
Date legacyDateUsingDateFrom = Date.from(
todaysDate.atStartOfDay(ZoneId.systemDefault())
.toInstant());
System.out.println(legacyDateUsingDateFrom); // prints Sun Jun 21 00:00:00 IST 2020
// Using Java.sql.Date.valueOf method to convert LocalDate to date
Date legacyDateUsingSqlDateValueOf = java.sql.Date.valueOf(todaysDate);
System.out.println(legacyDateUsingSqlDateValueOf); // prints 2020-06-21
}
}
Java Date to LocalDate
We may come across a situation as well where we need to convert Date to LocalDate in our daily work here is the example that can simply convert date to localdate.
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
public class DateToLocalDate {
public static void main(String[] args) {
// Using toInstant to convert Date to LocalDate
Date todaysDate = new Date();
LocalDate localDateUsingLegacyDate = todaysDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
System.out.println(localDateUsingLegacyDate); // 2020-06-21
// Using java.sql.Date to convert Date to LocalDate
LocalDate localDateUsingSqlDateConversion = new java.sql.Date(new java.util.Date().getTime()).toLocalDate();
System.out.println(localDateUsingSqlDateConversion); // 2020-06-21
}
}
Conclusion
In this post, we have seen
- how we can import LocalDate Class.
- how to create a LocalDate instance.
- how to get date information like dayOfMonth, dayOfWeek, etc.
- how to get past date using minus methods.
- how to get future dates using plus methods.
- how to use with methods to get a specific date.
- how to convert LocalDate to Date.
- how to convert Date to LocalDate.
That's it for the LocalDate Java class. As we can see LocalDate helps in doing operations like plus days, plus months, minus days, minus months and many others with respect to current date with easy methods which are very helpful and handy thus one must use LocalDate java class features in the current project.
With Java 8 we get a very rich API for working with date and time. The API can completely replace old classes like java.util.Date or java.util.Calendar with newer, more flexible classes. Due to mostly immutable classes, the new API helps in building thread-safe systems. Java8 has come up with many classes like LocalDate, LocalTime, LocalDateTime, Instant, Clock, etc. We will look at more classes in further posts.
Comments
Post a Comment
If you have any doubts, Please let me know.