Java Tutorials


Java 8 LocalDate Class

LocalDate class Usage

   LocalDate represents only date, i.e year ,month,day

Creating a LocalDate Object. LocalDate's

now()

method returns system's date.

of

method returns specific date of your choice. Both are static methods.
      		LocalDate date = LocalDate.now();
      		LocalDate date =LocalDate.of(2020,11,11);
      		LocalDate date =LocalDate.of(2020,Month.OCTOBER,11);
      		
      		System.out.println(date);
      		2020-11-11
      

Extract Year, Month and Day from LocalDate

    LocalDate Object has instance methods to get Year,Month and Day.

     getYear(), getDayOfMonth(),date.getDayOfWeek(), getMonth(), getMonthValue()

      
      

Add days ,months ,years to LocalDate

    plusDays, plusWeeks, plusMonths, plusYears

Add Days
      		LocalDate date =LocalDate,of(2010,11,11);
      		System.out.println(date.plusDays(20););
      		2011-12-01
      
Add Months
      		LocalDate date =LocalDate,of(2010,11,11);
      		System.out.println(date.plusMonths(12));
      		2011-11-11
      
Add Years
      		LocalDate date =LocalDate,of(2010,11,11);
      		System.out.println(date.plusyears(21));
      		2032-11-11
      		System.out.println(date.plusyears(-21));
		1990-11-11
      

Comparing LocalDate Objects

    LocalDate object implements Comparable interface. So date objects can be comparable with each other.

  • returns 0 means both dates are equal
  • -ve value date1 is less than date 2
  • +ve value date1 is greater than date2
	      	LocalDate date1 = LocalDate.of(2010,1,2);
	      	LocalDate date2 = LocalDate.of(1990,1,2);
	      	
	      	int value  =  date1.compareTo(date2);  //20
	      	date1 is greater than date2
	      	
	      	int value = date2.compareTo(date1);   //-20
	      	date2 is less than date1
      

LocalDate objects can be compared with other LocalDate Object using following function, which returns boolean value.

  • isAfter
  • isBefore
  • isEqual
	      	LocalDate date1 = LocalDate.of(2010,1,2);
	      	LocalDate date2 = LocalDate.of(1990,1,2);

		date1.isEqual(date2);    //false
		
		date1.isAfter(date2);     //true
		
		date1.isBefore(date2);    //false
      		
      

Parse LocalDate Object

      LocalDate Object can be converted into a String, or String into a LocalDate Object using parse method.

Parse method has 2 variants
  • parse(CharSequence text)
  • parse(CharSequence text, DateTimeFormatter formatter)

Both are static methods, which can be accessed without using LocalDate Object instance.

.parse(CharSequence text) example. Use this method only when date format is 'yyyy-mm-dd'

		String strDate = "1990-12-1";
		
		LocalDate date = LocalDate.parse( strDate );
		
		LocalDate Object  is constructed.
		
		date.getYear() ;   //1990
		
		date.getMonthValue();  //12
		
		date.getDayOfMonth();  //1
		
	


.parse(CharSequence text, DateTimeFormatter formatter) example.

Use this method ,Date in any format.DateTimeFormatter class located in package java.time.format.DateTimeFormatter It is a general class to format Date and Time .

	
		for ex:  format of the Dates
		      12Aug2012
		      Aug122012
		      Feb1st2012
		      2022yearmonthOctDay1
		      
		      to pase any of the above dates, programmer can use DateTimeFormatter class.
		      
		String strDate = "12Aug2012";
		
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMMyyyy")
		
		LocalDate date = LocalDate.parse( strDate, formatter );
		
		LocalDate Object  is constructed.
		
		date.getYear() ;   //2012
		
		date.getMonthValue();  //8
		
		date.getDayOfMonth();  //12
		
		
		String strDate = "Feb1st2012";
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMd'st'yyyy");
		LocalDate date = LocalDate.parse( strDate, formatter );
		
		
		//2012-02-01		
		
	

Example:Find a Month(s) ,Pay Day(1st day of the Month) falls on Sunday for a given Year

    Finding Months ,1st of the month falls on Sunday. In this example we Check every month's 1st is Sunday or Not. LocalDate creates a Date for a specific year. datesUntil method generates stream of LocalDates from starting of the Year to end of the Year. Filter condition checks is DayofMonth is 1 and DayOfWeek is SUNDAY, it returns TRUE only above condition is met, otherwise FALSE.
for YEAR 2023 , JANUARY and OCTOBER months Day 1st falls on SUNDAY

	import java.time.*;
	import java.util.stream.*;
	
		LocalDate date = LocalDate.of(2023,1,1)
		Stream<LocalDate> dates = date.datesUntil(LocalDate.of(2023,12,2))
		dates.filter(d ->{return  d.getDayOfMonth()==1 && d.getDayOfWeek().equals(DayOfWeek.SUNDAY);}).forEach(System.out::println)
2023-01-01
2023-10-01

	

Extract Year,Month,Day using get method

get method syntax:
public int get(TemporalField field)

TemporalField located in java.time.temporal package, which is used to query specified field in the locatedate object. If queried field is not valid , an exception is thrown, TemporalField is an interface, framework implemented class for this interface is ChronoField

		LocalDate date = LocalDate.of(1992,7,12)
		
		date.get(ChronoField.YEAR)  1992
		date.get(ChronoField.MONTH_OF_YEAR)  7
		date.get(ChronoField.DAY_OF_MONTH)  12
	

Add Years,Months,Days using plus method

plus method syntax:
	LocalDate plus(long amountToAdd, TemporalUnit unit)       
	LocalDate plus(TemporalAmount amountToAdd)	
       

TemporalUnit located in java.time.temporal package, Measurement of date & time is built on units, such as years,months,days etc., The instance of this interface represents the unit itself,rather than the amount of the unit.Framework implemented class for this interface is ChronoUnit.
TemporalAmount is an interface located in java.time.temporal package, This is an interface type for amount of time, like " 10yrs 3 months",framework implemented class for this interface is Duration and Period classes. Duration is based on time based object, Period is date based object

		LocalDate date = LocalDate.of(1992,7,12)
		
		using TemporalUnit
		
		//Add 10 years to date
		System.out.println(date.plus(10,ChronoUnit.YEARS))  2002-07-12
		//Add 5 months
		System.out.println(date.plus(5,ChronoUnit.MONTHS))  1997-12-12
		//Add 13 days to LocalDate
		System.out.println(date.plus(13,ChronoUnit.DAYS))   1997-07-25  
		
	

TemporalAmount interface implemented by Period class, Which can be used to add specified amount of date as shown below. Period maintains Date related information, like years,months and days, and it has equivalent static methods, like ofYears, ofMonths,ofDays

		LocalDate date = LocalDate.of(1992,7,12)
		
		using TemporalAmount implemented class Period
		
		//Add 10 years to date
		System.out.println(date.plus(Period.ofYears(10)))  2002-07-12
		//Add 5 months
		System.out.println(date.plus(Period.ofMonths(5)))  1997-12-12
		//Add 13 days to LocalDate
		System.out.println(date.plus(Period.ofDays(13))   1997-07-25  
		
	

Query Year,Month,Day of LocalDate object using query method

query method syntax:
R LocalDate.<R>query(TemporalQuery<R> query)

TemporalQuery located in java.time.temporal package, which is used to query specified field in the locatedate object. framework implemented class for this interface is TemporalQueries

TemporalQuery is a Functional Interface

		LocalDate date = LocalDate.of(1992,7,12)
		
	

Finding difference between two dates in terms of YEARS, MONTHS or DAYS

until method syntax:
       long LocalDate.until(Temporal endExclusive, TemporalUnit unit)
      

Temporal located in java.time.temporal package, All Date time classes implemented this interface. Until function takes 2 parameters, one is class which implemented Temporal interface, another one Class Which implemented TemporalUnit interface

Here we have LocalDate class implements temporal interface, ChronoUnit class implements TemporalUnit interface

		LocalDate date = LocalDate.of(1992,7,12)
		System.out.println(date.until(LocalDate.of(1995,7,12), ChronoUnit.YEARS)+" Years")
		3 Years
		System.out.println(date.until(LocalDate.of(1995,7,12), ChronoUnit.MONTHS)+" Months")
		36 Months

		System.out.println(date.until(LocalDate.of(1995,7,12), ChronoUnit.DAYS)+" Days")
		1095  Days



	

ADS