Java LocalDate

By Arvind Rai, May 07, 2019
This page will walk through java.time.LocalDate example. LocalDate introduced in Java 8, represents a date in the format yyyy-MM-dd such as 2018-12-05. It does not store time or time-zone. LocalDate is an immutable class and it is the description of the date such as birthdays. LocalDate is a value-based class and to compare two instances of LocalDate, we should use its equals method. We can fetch many other fields of the date from LocalDate such as day-of-year, day-of-week, month-of-year etc. The format of LocalDate can be changed using its format method passing DateTimeFormatter. The methods of LocalDate is now, atTime, format, getDayOfMonth, getDayOfWeek, minus, plus, equals, compareTo etc.
For example, get current date.
LocalDate localDate = LocalDate.now(); 
Output is 2018-12-05. Now change format.
String formattedDate = localDate.format(DateTimeFormatter.ofPattern("MMM dd, yyyy")); 
Output Dec 05, 2018.
In Java 9 LocalDate has been added with more methods such as ofInstant, datesUntil, toEpochSecond. Here on this page we will discuss LocalDate and its methods with examples.

Initializing LocalDate

LocalDate gives output in year-month-day format i.e yyyy-MM-dd. We can initialize LocalDate using following static methods of LocalDate.
1. now(): Gives LocalDate instance with current date from the system clock in the default time-zone.
LocalDate localDate = LocalDate.now();
System.out.println(localDate); 
Find the output.
2018-12-05 
2. now(Clock clock): Gives LocalDate instance with current date obtaining from specified Clock.
LocalDate localDate = LocalDate.now(Clock.systemUTC()); 
Clock.systemUTC() will return Clock instance.
3. now(ZoneId zone): Gives LocalDate instance with current date from the system clock in the specified time zone.
LocalDate localDate = LocalDate.now(ZoneId.systemDefault()); 
4. of(int year, int month, int dayOfMonth: Gives LocalDate instance from the given year, month and day of month as int.
LocalDate localDate = LocalDate.of(2018, 11, 30); 
Output is 2018-11-30
5. of(int year, Month month, int dayOfMonth): Gives LocalDate instance from the given year as int, month as Month and day of month as int.
LocalDate localDate = LocalDate.of(2018, Month.NOVEMBER, 30); 
Output is 2018-11-30
6. ofEpochDay(long epochDay): Gives LocalDate instance from the given epoch day count.
LocalDate localDate = LocalDate.ofEpochDay(500); 
Output is 1971-05-16
7. ofInstant(Instant instant, ZoneId zone): Gives LocalDate instance from the given Instant and ZoneId.
LocalDate localDate = LocalDate.ofInstant(Instant.now(), ZoneId.systemDefault()); 
ofInstant has been introduced in Java 9.
8. ofYearDay(int year, int dayOfYear): Gives LocalDate instance from the given year and day of year as int.
LocalDate localDate = LocalDate.ofYearDay(2018, 02); 
Output is 2018-01-02
9. parse(CharSequence text): Gives LocalDate instance from the given text string such as "2018-10-01".
LocalDate localDate = LocalDate.parse("2018-10-01"); 
Output is 2018-10-01
10. parse(CharSequence text, DateTimeFormatter formatter): Gives LocalDate instance from the given text string in the given format. The output LocalDate will be in yyyy-MM-dd format.
LocalDate localDate = LocalDate.parse("15-03-2018", DateTimeFormatter.ofPattern("dd-MM-yyyy")); 
Output is 2018-03-15
11. from(TemporalAccessor temporal): Gives LocalDate instance from given temporal object.
LocalDate localDate = LocalDate.from(LocalDate.now()); 

LocalDate "plus" Methods

Find the LocalDate methods to add date value by given amount.
1. plus(long amountToAdd, TemporalUnit unit): Returns LocalDate instance by adding the given amount.
package com.concretepage;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

public class LocalDateDemo {
  public static void main(String[] args) {
	LocalDate localDate1 = LocalDate.now();
	System.out.println(localDate1);
	
	LocalDate localDate2 = localDate1.plus(15, ChronoUnit.DAYS);
	System.out.println(localDate2);
  }
} 
Find the output.
2018-12-02
2018-12-17 
In the above example we added 15 days into current date.
2. plus(TemporalAmount amountToAdd): Returns LocalDate instance by adding specified TemporalAmount.
LocalDate localDate1 = LocalDate.now();
System.out.println(localDate1);
	
LocalDate localDate2 = localDate1.plus(Period.ofDays(15));
System.out.println(localDate2); 
Find the output.
2018-12-02
2018-12-17 
In the above code we added 15 days to localDate1 and got localDate2 as the instance of LocalDate.
3. plusDays(long daysToAdd): Returns LocalDate instance by adding specified number of days.
LocalDate localDate1 = LocalDate.parse("2018-11-05");
LocalDate localDate2 = localDate1.plusDays(15);
System.out.println(localDate2); 
Output is 2018-11-20
4. plusWeeks(long weeksToAdd): Returns LocalDate instance by adding specified number of weeks.
LocalDate localDate1 = LocalDate.parse("2018-11-05");
LocalDate localDate2 = localDate1.plusWeeks(5);
System.out.println(localDate2); 
Output is 2018-12-10
5. plusMonths(long monthsToAdd): Returns LocalDate instance by adding specified number of months.
LocalDate localDate1 = LocalDate.parse("2018-11-05");
LocalDate localDate2 = localDate1.plusMonths(12);
System.out.println(localDate2); 
Output is 2019-11-05
6. plusYears(long yearsToAdd): Returns LocalDate instance by adding specified number of years.
LocalDate localDate1 = LocalDate.parse("2018-11-05");
LocalDate localDate2 = localDate1.plusYears(2);
System.out.println(localDate2); 
Output is 2020-11-05

LocalDate "minus" Methods

Find the LocalDate methods to subtract date value by given amount.
1. minus(long amountToSubtract, TemporalUnit unit): Returns LocalDate instance by subtracting the given amount.
package com.concretepage;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

public class LocalDateDemo {
  public static void main(String[] args) {
	LocalDate localDate1 = LocalDate.now();
	System.out.println(localDate1);

	LocalDate localDate2 = localDate1.minus(15, ChronoUnit.DAYS);
	System.out.println(localDate2);
  }
} 
Find the output.
2018-12-02
2018-11-17 
In the above example we subtracted 15 days from current date.
2. minus(TemporalAmount amountToSubtract): Returns LocalDate instance by subtracting specified TemporalAmount.
LocalDate localDate1 = LocalDate.now();
System.out.println(localDate1);

LocalDate localDate2 = localDate1.minus(Period.ofDays(15));
System.out.println(localDate2); 
Find the output.
2018-12-02
2018-11-17 
In the above code we subtracted 15 days from localDate1 and got localDate2 as the instance of LocalDate.
3. minusDays(long daysToSubtract): Returns LocalDate instance by subtracting specified number of days.
LocalDate localDate1 = LocalDate.parse("2018-11-05");
LocalDate localDate2 = localDate1.minusDays(15);
System.out.println(localDate2); 
Output is 2018-10-21
4. minusWeeks(long weeksToSubtract): Returns LocalDate instance by subtracting specified number of weeks.
LocalDate localDate1 = LocalDate.parse("2018-11-05");
LocalDate localDate2 = localDate1.minusWeeks(5);
System.out.println(localDate2); 
Output is 2018-10-01
5. minusMonths(long monthsToSubtract): Returns LocalDate instance by subtracting specified number of months.
LocalDate localDate1 = LocalDate.parse("2018-11-05");
LocalDate localDate2 = localDate1.minusMonths(12);
System.out.println(localDate2); 
Output is 2017-11-05
6. minusYears(long yearsToSubtract): Returns LocalDate instance by subtracting specified number of years.
LocalDate localDate1 = LocalDate.parse("2018-11-05");
LocalDate localDate2 = localDate1.minusYears(2);
System.out.println(localDate2); 
Output is 2016-11-05

LocalDate "with" Methods

Find the LocalDate methods that will return LocalDate adjusting with specified values or setting a new value to a given date field.
1. with(TemporalAdjuster adjuster): Returns LocalDate instance adjusting with given TemporalAdjuster.
LocalDate localDate1 = LocalDate.now();
System.out.println(localDate1);
	
LocalDate localDate2 = localDate1.with(DayOfWeek.SUNDAY);
System.out.println(localDate2); 
Find the output.
2018-12-03
2018-12-09 
In the above code we changed day of the current date using with method. In the current date output, it is Monday. By adjusting with Sunday, we get a new date.
2. with(TemporalField field, long newValue): Returns LocalDate instance with specified field to a new value.
LocalDate localDate1 = LocalDate.now();
System.out.println(localDate1);
	
LocalDate localDate2 = localDate1.with(ChronoField.YEAR, 2017);
System.out.println(localDate2); 
Find the output.
2018-12-03
2017-12-03 
In the above code we set new value for year.
3. withDayOfMonth(int dayOfMonth): Returns LocalDate instance by changing day of month with given value.
LocalDate localDate1 = LocalDate.now();
System.out.println(localDate1);
	
LocalDate localDate2 = localDate1.withDayOfMonth(10);
System.out.println(localDate2); 
Find the output.
2018-12-03
2018-12-10 
4. withDayOfYear(int dayOfYear): Returns LocalDate instance by changing day of year with given value. Valid values for day of year is 1 to 365 and for leap year it is 1 to 366.
LocalDate localDate1 = LocalDate.now();
System.out.println(localDate1);
	
LocalDate localDate2 = localDate1.withDayOfYear(110);
System.out.println(localDate2); 
Find the output.
2018-12-03
2018-04-20 
In the above example we want to set 110 in current date. Output will be created in the way that year will not change and month and day will be obtained from 110 days starting from January.
5. withMonth(int month): Returns LocalDate instance by changing month of year with given value. Valid values are 1 to 12.
LocalDate localDate1 = LocalDate.now();
System.out.println(localDate1);
	
LocalDate localDate2 = localDate1.withMonth(6);
System.out.println(localDate2); 
Find the output.
2018-12-03
2018-06-03 
6. withYear(int year): Returns LocalDate instance by changing year with given value.
LocalDate localDate1 = LocalDate.now();
System.out.println(localDate1);
	
LocalDate localDate2 = localDate1.withYear(2017);
System.out.println(localDate2); 
Find the output.
2018-12-03
2017-12-03 

LocalDate "get" Methods

Create a LocalDate instance as following.
LocalDate localDate = LocalDate.now();
System.out.println(localDate); 
Suppose it gives following value.
2018-12-03 
1. get(TemporalField field): Gets the value of specified field as int.
int val = localDate.get(ChronoField.YEAR);
System.out.println(val); 
Output
2018 
2. getChronology(): Gets the chronology of this date.
IsoChronology val = localDate.getChronology(); 
3. getDayOfMonth(): Gets day of month as int.
int val = localDate.getDayOfMonth();
System.out.println(val); 
Output
3 
4. getDayOfWeek(): Gets the day of week field as DayOfWeek.
DayOfWeek val = localDate.getDayOfWeek();
System.out.println(val.name()); 
Output
MONDAY 
5. getDayOfYear(): Gets the days of year field as int. It can return from 1 to 365 or 366 for leap year.
int val = localDate.getDayOfYear();
System.out.println(val); 
Output
337 
6. getEra(): Gets the era for this date as IsoEra.
IsoEra val = localDate.getEra(); 
7. getLong(TemporalField field): Gets the value of specified field as long.
long val = localDate.getLong(ChronoField.YEAR);
System.out.println(val); 
Output
2018 
8. getMonth(): Gets the month of the year from this date as Month.
Month val = localDate.getMonth();
System.out.println(val.name()); 
Output
DECEMBER 
9. getMonthValue(): Gets the month of year field as int from 1 to 12.
int val = localDate.getMonthValue();
System.out.println(val); 
Output
12 
10. getYear(): Gets the year field as int.
int val = localDate.getYear();
System.out.println(val); 
Output
2018 


LocalDate format()

The default date format of LocalDate is yyyy-MM-dd. The format method formats the date using specified formatter. Find its declaration.
String format(DateTimeFormatter formatter) 
Find the example.
package com.concretepage;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class LocalDateDemo {
  public static void main(String[] args) {
	LocalDate localDate = LocalDate.parse("2018-02-18");
	String formattedDate = localDate.format(DateTimeFormatter.ofPattern("MMM dd, yyyy"));
	System.out.println(formattedDate);
  }
} 
Output
Feb 18, 2018 

LocalDate atTime()

atTime method combines LocalDate with given time and returns LocalDateTime instance. We can pass following arguments to atTime method.
atTime(int hour, int minute)
atTime(int hour, int minute, int second)
atTime(int hour, int minute, int second, int nanoOfSecond)
atTime(LocalTime time) 
Find the example.
package com.concretepage;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

public class LocalDateDemo {
  public static void main(String[] args) {
	LocalDate localDate = LocalDate.parse("2018-05-02");
	System.out.println(localDate);
	
	//hour and minute
	LocalDateTime localDateTime = localDate.atTime(16, 50);
	System.out.println(localDateTime);
	
	//hour, minute and second
	localDateTime = localDate.atTime(16, 50, 20);
	System.out.println(localDateTime);	

	//hour, minute, second and nanoOfSecond	
	localDateTime = localDate.atTime(16, 50, 20, 300);
	System.out.println(localDateTime);	
	
	//Using LocalTime
	localDateTime = localDate.atTime(LocalTime.now());
	System.out.println(localDateTime);		
  }
} 
Output
2018-05-02
2018-05-02T16:50
2018-05-02T16:50:20
2018-05-02T16:50:20.000000300
2018-05-02T15:26:07.637805900 
We can also pass OffsetTime to atTime that will return OffsetDateTime instance.
OffsetDateTime  offsetDateTime  = localDate.atTime(OffsetTime.now());
System.out.println(offsetDateTime); 
Output
2018-05-02T19:27:14.761376600+05:30 

LocalDate atStartOfDay()

atStartOfDay method combines the LocalDate with the time of midnight to create LocalDateTime instance at the start of this date. To get ZonedDateTime instance, we need to pass ZoneId instance to atStartOfDay method. Find the declarations of atStartOfDay method.
LocalDateTime atStartOfDay()
ZonedDateTime atStartOfDay(ZoneId zone) 
Find the example.
package com.concretepage;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class LocalDateDemo {
  public static void main(String[] args) {
	LocalDate localDate = LocalDate.now();
        LocalDateTime localDateTime = localDate.atStartOfDay();
	System.out.println(localDateTime);
	
	ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());
	System.out.println(zonedDateTime);	
  }
} 
Output
2018-12-03T00:00
2018-12-03T00:00+05:30[Asia/Calcutta] 
We can observe that time value is of start of day.

LocalDate isAfter(), isBefore() and isEqual()

isAfter(ChronoLocalDate other): Checks if this date is after given date.
isBefore(ChronoLocalDate other): Checks if this date is before given date.
isEqual(ChronoLocalDate other): Checks if this date is equal to given date.

Find the example.
package com.concretepage;
import java.time.LocalDate;

public class LocalDateDemo {
  public static void main(String[] args) {
	LocalDate localDate1 = LocalDate.parse("2018-03-18");
	LocalDate localDate2 = LocalDate.parse("2018-05-12");

	System.out.println(localDate1.isAfter(localDate2));
	System.out.println(localDate1.isBefore(localDate2));
	System.out.println(localDate1.isEqual(localDate2));
  }
} 
Output
false
true
false 

LocalDate isLeapYear(), isSupported()

isLeapYear(): Checks if year is leap year.
isSupported(TemporalField field): Checks if given field is supported. Before fetching any field from date we can check if that field is supported otherwise we may get error.
isSupported(TemporalUnit unit): Checks if given unit is supported. Before using plus and minus, we can check if given unit is supported otherwise we may get error

Find the example.
package com.concretepage;
import java.time.LocalDate;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;

public class LocalDateDemo {
  public static void main(String[] args) {
	LocalDate localDate = LocalDate.parse("2016-03-18");
	System.out.println(localDate.isLeapYear());
	System.out.println(localDate.isSupported(ChronoField.DAY_OF_MONTH));
	System.out.println(localDate.isSupported(ChronoUnit.HOURS));	
  }
} 
Output
true
true
false 

LocalDate lengthOfMonth(), lengthOfYear()

lengthOfMonth(): Gives length of month such as 28, 29, 30, 31.
lengthOfYear(): Gives length of year either 365 or 366 (leap year).

Find the example.
package com.concretepage;
import java.time.LocalDate;

public class LocalDateDemo {
  public static void main(String[] args) {
	LocalDate localDate = LocalDate.parse("2018-02-18");
	System.out.println(localDate.lengthOfMonth());
	System.out.println(localDate.lengthOfYear());
  }
} 
Output
28
365 

LocalDate datesUntil()

datesUntil method in LocalDate has been introduced in Java 9. datesUntil method returns sequential ordered stream of dates excluding the given date. We can also pass period to set incremental step. We get stream of dates starting from this date until specified date. Specified date will be excluded in the result. datesUntil is declared as following.
Stream<LocalDate> datesUntil(LocalDate endExclusive)
Stream<LocalDate> datesUntil(LocalDate endExclusive, Period step) 
Find the example.
package com.concretepage;
import java.time.LocalDate;
import java.time.Period;
import java.util.stream.Stream;

public class LocalDateDemo {
  public static void main(String[] args) {
	LocalDate localDate = LocalDate.parse("2018-02-18");
	
        System.out.println("--- With LocalDate ---");
	Stream<LocalDate> localDateStream = localDate.datesUntil(LocalDate.parse("2018-02-22"));
	localDateStream.forEach(date -> System.out.println(date));
	
        System.out.println("--- With LocalDate and Period ---");
	localDateStream = localDate.datesUntil(LocalDate.parse("2018-02-22"), Period.ofDays(2));
	localDateStream.forEach(date -> System.out.println(date));    
  }
} 
Output
--- With LocalDate ---
2018-02-18
2018-02-19
2018-02-20
2018-02-21
--- With LocalDate and Period ---
2018-02-18
2018-02-20 

LocalDate until()

1. Calculates the period between this date and specified date as Period.
Period until(ChronoLocalDate endDateExclusive) 
2. Calculates the amount of time until specified date (exclusive).
long until(Temporal endExclusive, TemporalUnit unit) 
Find the example.
package com.concretepage;
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;

public class LocalDateDemo {
  public static void main(String[] args) {
    LocalDate localDate = LocalDate.parse("2018-02-18");
	
    Period period = localDate.until(LocalDate.parse("2018-03-28"));
    System.out.println(period.getDays());
    
    long val = localDate.until(LocalDate.parse("2018-03-28"), ChronoUnit.DAYS);
    System.out.println(val);
  }
} 
Output
10
38 

LocalDate compareTo() and equals()

compareTo(ChronoLocalDate other): Compares this date to specified date.
equals(Object obj): Checks if this date is equal to specified date.

Find the example.
LocalDate localDate = LocalDate.parse("2018-02-18");
System.out.println(localDate.equals(LocalDate.parse("2018-02-18")));
System.out.println(localDate.compareTo(LocalDate.parse("2018-02-25"))); 
Output
true
-7 

LocalDate adjustInto()

adjustInto method adjusts the specified temporal object to have the same date as this object. Find the example.
package com.concretepage;
import java.time.LocalDate;
import java.time.temporal.Temporal;

public class LocalDateDemo {
  public static void main(String[] args) {
	LocalDate localDate = LocalDate.parse("2018-02-18");
	Temporal temporalObj = LocalDate.parse("2017-03-20");
	
	temporalObj = localDate.adjustInto(temporalObj);
	System.out.println(temporalObj);
  }
} 
Output
2018-02-18 
We can see that temporalObj has different date value to localDate. But after adjusting temporalObj with localDate, both are same.

LocalDate query()

query method queries this date using specified query.
TemporalUnit unit = localDate.query(TemporalQueries.precision()); 
Output
Days 
TemporalQueries.precision() queries for smallest supported unit. It returns the instance of TemporalQuery.

LocalDate range()

range gives the range of valid values for the specified field.
LocalDate localDate = LocalDate.parse("2018-02-18");
	
ValueRange vrange = localDate.range(ChronoField.DAY_OF_MONTH);
System.out.println(vrange);
    
vrange = localDate.range(ChronoField.DAY_OF_WEEK);
System.out.println(vrange); 
Output
1 - 28
1 – 7 
In the above code, date is "2018-02-18". We can see that the date range for the February in this date year can be 1 – 28 and day of week is 1 – 7.

LocalDate toEpochDay() and toEpochSecond()

toEpochDay(): Converts this date to epoch day and returns long value.
toEpochSecond(LocalTime time, ZoneOffset offset): Converts this date to the number of seconds since the epoch of 1970-01-01T00:00:00Z and returns long value. In has been introduced in Java 9.

Find the example.
LocalDate localDate = LocalDate.parse("2018-02-18");
System.out.println(localDate.toEpochDay());
System.out.println(localDate.toEpochSecond(LocalTime.now(), ZoneOffset.MAX)); 
Output
17580
1518921065 

Reference

Class LocalDate
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us