Showing posts with label Date Time API. Show all posts
Showing posts with label Date Time API. Show all posts

Sunday, July 20, 2025

Java 8 - How to convert Calendar to LocalDateTime?

1. Overview

In this article, You'll learn how to convert Calendar to LocalDateTime object in java 8 DateTime api

LocalDateTime api can be used completely replacement to the Date class as all features of Date functions are done in a simple and precise way such as adding minutes to the current date.

Java 8 - How to convert Calendar to LocalDateTime?

Friday, December 3, 2021

Java Calendar Add

1. Introduction

In this tutorial, we'll learn how to add or subtract the time units from the Calendar object in java.

java.util.Calendar.add() method is used to increase or reduce the specified amount of time to the given calendar field.


Java Calendar Add

Thursday, November 25, 2021

Java 8 – Convert LocalDateTime to Timestamp & Vice Versa

1. Overview

In this tutorial, We'll learn how to convert LocalDateTime object into the Timestamp in java 8 new Date Time API.

If you are new to Java 8 or above, It is recommended to read java 8 new date-time API in java indepth 

And also we will learn how to convert LocalDate to TimeStamp in java 8.

Java 8 – Convert LocalDateTime to Timestamp & Vice Versa

Monday, November 22, 2021

Java Get Current Timestamp

1. Overview

In this tutorial, We'll learn how to get the current timestamp in java in various ways.

Let us jump into the right examples with JDK 8 and older jdk.


Java Get Current Timestamp

Saturday, January 23, 2021

Java LocalDate atStartOfDay() Example

1. Overview

In this tutorial, We'll learn how to use LocalDate.atStartOfDay() method in java 8. This is the newly added method in Date Time API in java 8.

atStartOfDay() method does appends the might night date with time part as 00:00 to LocalDate.

This is an overloaded method and available in two versions as below. 

public LocalDateTime atStartOfDay()

public ZonedDateTime atStartOfDay(ZoneId zone)


public LocalDateTime atStartOfDay(): This method appends the mid night to the LocalDate and returns it as LocalDateTime object with time default values as zero's.

public ZonedDateTime atStartOfDay(ZoneId zone): This method takes ZoneId instance for time zone value and converts the LocalDate to ZonedDateTime by adding the time part as zero's.

Let us explore the examples on these two methods with examples.

Java LocalDate atStartOfDay() Example



But, you need to remember one core point is that LocalDate does not store the time part but to convert it to LocalDateTime, we need to add time part. This adding the time part is done with atStartOfDay() method.


2. Java 8 LocalDate.atStartOfDay() - LocalDate to LocalDateTime


Understand the example program using atStartOfDay() method with zero parameters to convert localdate to LocalDateTime object to mid night and adding time units with default values as 0.

package com.javaprogramto.java8.dates.localdate;

import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * Example for public LocalDateTime atStartOfDay() method in LocalDate class in
 * java 8.
 * 
 * @author JavaProgramTo.com
 *
 */

public class LocalDateAtStartOfDayExamples {

	public static void main(String[] args) {
		// Example 1

		// creating LocalDate object
		LocalDate localDate1 = LocalDate.now();

		// converting LocalDate object to LocalDateTime object
		LocalDateTime localDateTime1 = localDate1.atStartOfDay();

		// printing the LocalDate, LocalDateTime objects
		System.out.println("localDate1 : " + localDate1);
		System.out.println("localDateTime1 : " + localDateTime1);

		// Example 2

		// creating LocalDate object
		LocalDate localDate2 = LocalDate.of(2023, 02, 02);

		// converting LocalDate object to LocalDateTime object
		LocalDateTime localDateTime2 = localDate2.atStartOfDay();

		// printing the LocalDate, LocalDateTime objects
		System.out.println("localDate2 : " + localDate2);
		System.out.println("localDateTime2 : " + localDateTime2);
	}
}

Output:
localDate1 : 2020-12-07
localDateTime1 : 2020-12-07T00:00
localDate2 : 2023-02-02
localDateTime2 : 2023-02-02T00:00

3. Java 8 LocalDate.atStartOfDay(ZoneId z) - LocalDate to ZonedDateTime


Next, example on how to convert LocalDate to ZonedLocalDate in java 8 with atStartOfDay() method that takes ZoneId as argument.

This method also works by adding time units as zero but it converts the date part as per the given timezone id.

In the below example, we have tried with the system timezone, Singapore and EST time zone dates.

package com.javaprogramto.java8.dates.localdate;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;

/**
 * Example for public ZonedDateTime atStartOfDay(ZoneId zoneid) method in
 * LocalDate class in java 8.
 * 
 * @author JavaProgramTo.com
 *
 */

public class LocalDateAtStartOfDayZoneIdExamples {

	public static void main(String[] args) {
		// Example 1 - IST

		// creating LocalDate object
		LocalDate localDate1 = LocalDate.now();

		// Getting the default timezone from system.
		ZoneId defaultId = ZoneId.systemDefault();

		// converting LocalDate object to ZonedDateTime object using timezone.
		ZonedDateTime zonedDateTime1 = localDate1.atStartOfDay(defaultId);

		// printing the LocalDate, ZonedDateTime objects
		System.out.println("localDate1 : " + localDate1);
		System.out.println("zonedDateTime1 : " + zonedDateTime1);

		// Example 2 - EST

		// creating LocalDate object
		LocalDate localDate2 = LocalDate.of(2023, 02, 02);

		// Getting the EST timezone from system.
		ZoneId timezoneESTId = ZoneId.of("US/Eastern");

		// converting LocalDate object to ZonedDateTime object using est zone id;
		ZonedDateTime zonedDateTime2 = localDate2.atStartOfDay(timezoneESTId);

		// printing the LocalDate, ZonedDateTime objects
		System.out.println("localDate2 : " + localDate2);
		System.out.println("zonedDateTime2 : " + zonedDateTime2);

		// Example 2 - Singapore

		// creating LocalDate object
		LocalDate localDate3 = LocalDate.of(2023, 02, 02);

		// Getting the Asia/Singapore timezone from system.
		ZoneId timezoneSingaporeId = ZoneId.of("Asia/Singapore");

		// converting LocalDate object to ZonedDateTime object using Asia/Singapore zone id;
		ZonedDateTime zonedDateTime3 = localDate3.atStartOfDay(timezoneSingaporeId);

		// printing the LocalDate, ZonedDateTime objects
		System.out.println("localDate3 : " + localDate3);
		System.out.println("zonedDateTime3 : " + zonedDateTime3);
	}
}
Output:
localDate1 : 2020-12-07
zonedDateTime1 : 2020-12-07T00:00+05:30[Asia/Kolkata]
localDate2 : 2023-02-02
zonedDateTime2 : 2023-02-02T00:00-05:00[US/Eastern]
localDate3 : 2023-02-02
zonedDateTime3 : 2023-02-02T00:00+08:00[Asia/Singapore]
From the output, We can see that timezone is added in the returned ZonedDateTime object and time units are 00:00 values.


4. Conclusion


In this article, we've seen how to use LocalDate.atStartOfDay() method with examples to convert LocalDate object to LocalDateTime and ZoneDateTime objects in java 8.


Friday, January 1, 2021

How To Get Current Date, Time and Timestamp In Java 8?

1. Overview

In this article, we will learn how to get current date, time and timestamp in java 8. 

Let us explore the java 8 new classes LocalDateTime, LocalDate, LocalTime and Instant to work with date and time values of Date Time api.

How To Get Current Date, Time and Timestamp In Java 8?



2. How to get current date in java 8


Use java.time.LocalDate class to get the current date in format of "yyyy-MM-dd" using now() method.

And also we can get the current date from any timezone using now(ZoneId.of()).

Finally, let us convert LocalDateTime to LocalDate object using toLocalDate() method.

In the below example. we have shown the different ways to retrieve the date object in java 8.
package com.javaprogramto.java8.dates.currentdate;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;

public class CurrentDate {

	public static void main(String[] args) {
		
		// getting the current date from LocalDate.now() method
		LocalDate currentDate = LocalDate.now();
		
		System.out.println("Current Date from LocalDate : "+currentDate);
		
		// Getting the current daet in Gmt +5
		LocalDate gmtPlus5 = LocalDate.now(ZoneId.of("GMT+05"));
		
		System.out.println("Current time in GMT +05:00 : "+gmtPlus5);
		
		// Gettting the date from LocalDateTime object.
		LocalDateTime localDateTime = LocalDateTime.now();
		LocalDate fromLocalDateTime = localDateTime.toLocalDate();
		System.out.println("From LocalDateTime : "+fromLocalDateTime);
	}
}

Output:
Current Date from LocalDate : 2021-01-01
Current time in GMT +05:00 : 2021-01-01
From LocalDateTime : 2021-01-01

In the output, we could see the same date because timezone date is falling the current date even adding +5 hours. If we are at the end of the day then you can see the different date.

3. How to get current time in java 8


To retrieve the only time part, we can use java.time.LocalTime class. LocalTime.now() method gets the time parts from system date in format hh:mm:ss.sssss.

Use now(ZoneId.of()) method returns the time in the given timezone.

And also we can get the time from LocalDateTime object using toLocalTime() method.

package com.javaprogramto.java8.dates.currentdate;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;

public class CurrentTime {

	public static void main(String[] args) {
		
		// getting the current date from LocalTime.now() method
		LocalTime currentDate = LocalTime.now();
		
		System.out.println("Current time from LocalTime in IST (+05:30): "+currentDate);
		
		// Getting the current daet in Gmt +5
		LocalTime gmtPlus5 = LocalTime.now(ZoneId.of("GMT+06:30"));
		
		System.out.println("Current time in GMT +05:00 : "+gmtPlus5);
		
		// Gettting the date from LocalTimeTime object.
		LocalDateTime LocalTimeTime = LocalDateTime.now();
		LocalTime fromLocalTimeTime = LocalTimeTime.toLocalTime();
		System.out.println("From LocalDateTime : "+fromLocalTimeTime);
	}
}

Output:
Current time from LocalTime in IST (+05:30): 17:52:08.567623
Current time in GMT +05:00 : 18:52:08.568073
From LocalDateTime : 17:52:08.568161

4. How to get current timestamp in java 8


By using java.time.Instant class to get the current timestamp in milli seconds and seconds.

Use Insant.toEpochMilli() and Instant.getEpochSecond() methods to get the current time in milliseconds and seconds respectively.

package com.javaprogramto.java8.dates.currentdate;

import java.time.Instant;

public class CurrentTimeStamp {

	public static void main(String[] args) {
		
		// getting the current timestamp from Instant.now() method
		Instant currentInstant = Instant.now();
		
		// getting the current time in milliseoconds from Instant
		long timeInMillis = currentInstant.toEpochMilli();
		
		System.out.println("Current timestamp in milli seconds "+timeInMillis);

		// Getting the current instant in seconds
		long timeInSeconds = currentInstant.getEpochSecond();
		
		System.out.println("Current timestamp in seconds : "+timeInSeconds);
	}
}

Output:
Current timestamp in milli seconds 1609504761862
Current timestamp in seconds : 1609504761

5. Conclusion


In this article, we've seen how to get the current date, time and timestamp objects using java 8 api.


Java 8 LocalDate Class With Examples

1. Overview

In this tutorial, you'll learn how to use LocalDate class in java 8 Date Time API and its methods with example programs.

In java 8, LocalDate class is an immutable class to represent the date with the default format of "yyyy-MM-dd".

And LocalDate does not represent the time part of date or timezone.

This is mainly used to store the date of birth or date of join because this object works with only with year, month and day but not with the hours, minutes and seconds.

Java 8 LocalDate Class With Examples


2. Java 8 LocalDate Class

This class is defined as final class in the api and implements Temporal, TemporalAdjuster, ChronoLocalDate, Serializable interfaces.

How to get the current date and time in java 8?

LocalDate class has many useful methods which reduces the manual work to write the date utility methods.

below are the few methods which are frequently used by the developers.

LocalDate of(int year, int month, int dayOfMonth): Creates a new LocalDate object with the given date parameters.

LocalDateTime atTime(int hour, int minute): It is used to combine this date with a time to create a LocalDateTime.

int compareTo(ChronoLocalDate other): It is used to compares this date to another date.

boolean equals(Object obj): It is used to check if this date is equal to another date.

String format(DateTimeFormatter formatter): It is used to format this date using the specified formatter.

int get(TemporalField field): It is used to get the value of the specified field from this date as an int.

boolean isLeapYear(): It is used to check if the year is a leap year, according to the ISO proleptic calendar system rules.

LocalDate minusDays(long daysToSubtract): It is used to return a copy of this LocalDate with the specified number of days subtracted.

LocalDate minusMonths(long monthsToSubtract): It is used to return a copy of this LocalDate with the specified number of months subtracted.

static LocalDate now(): It is used to obtain the current date from the system clock in the default time-zone.

LocalDate plusDays(long daysToAdd): It is used to return a copy of this LocalDate with the specified number of days added.

LocalDate plusMonths(long monthsToAdd): It is used to return a copy of this LocalDate with the specified number of months added.


3. LocalDate Examples

Next, let us see the how to use these methods to work with dates such as adding days, comparing the dates, checking the leap year. etc.

All methods of LocalDate class recreates the new object the modified data.

To see the contents of LocalDate object, write the object onto the log or console. Because, toString() method is overridden in this class and it returns the date in the redable format "yyyy-MM-dd"

3.1 Example 1: Create Objects for LocalDate

LocalDate has 2 methods to create the date objects and those are now() and of() methods.

package com.javaprogramto.java8.dates.localdate;

import java.time.LocalDate;

public class LocalDateCreation {

	public static void main(String[] args) {

		// Dates creation with now() and of() methods.
		LocalDate currentDate = LocalDate.now();
		LocalDate futureDate = LocalDate.of(2025, 10, 10);

		// printing the dates.
		System.out.println("Current date : " + currentDate);
		System.out.println("Future date : " + futureDate);

	}

} 

Output:

Current date : 2020-11-23
Future date : 2025-10-10
 

3.2 Example 2:  Adding days and getting next, previous days

Use plusDays() and minusDays() methods to get the next or previous days.

And you go add or go back to a particular day using these two methods.

package com.javaprogramto.java8.dates.localdate;

import java.time.LocalDate;

public class AddingDaysExample {

	public static void main(String[] args) {
		// creating current date time
		LocalDate currentDate = LocalDate.now();
		
		// Getting the next date
		LocalDate nextDay = currentDate.plusDays(1);
		
		// Getting the previous date
		LocalDate previousDay = currentDate.minusDays(1);
		
		System.out.println("Current date : "+currentDate);
		System.out.println("Next date : "+nextDay);
		System.out.println("Previous date : "+previousDay);
	}
}
 

Output:

Current date : 2020-11-23
Next date : 2020-11-24
Previous date : 2020-11-22
 

3.3 Example 3:  Checking Leap Year

Call isLeapYear() method from LocalDate class. This method returns boolean as true if the year is leap year else false.

package com.javaprogramto.java8.dates.localdate;

import java.time.LocalDate;

public class LeapYearExample {
	public static void main(String[] args) {
		//	Example 1 - leap year checking
		LocalDate date1 = LocalDate.now();
		boolean isLeapYear = date1.isLeapYear();
		System.out.println(date1 + " is leap year ? " + isLeapYear);

		//	Example 2
		LocalDate date2 = LocalDate.of(2000, 01, 01);
		isLeapYear = date2.isLeapYear();
		System.out.println(date2 + " is leap year ? " + isLeapYear);

		//	Example 3
		LocalDate date3 = LocalDate.of(2006, 01, 01);
		isLeapYear = date3.isLeapYear();
		System.out.println(date3 + " is leap year ? " + isLeapYear);
	}
}

 

Output:

2020-11-23 is leap year ? true
2000-01-01 is leap year ? true
2006-01-01 is leap year ? false

 

3.4 Example 4: Convert LocalDate to String

Use format() method to convert LocalDate to String in java 8.

package com.javaprogramto.java8.dates.localdate;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class LocalDateToStringExample {

	public static void main(String[] args) {

		// Converting LocalDate to String
		// Example 1
		LocalDate date1 = LocalDate.now();
		String date1Str = date1.format(DateTimeFormatter.ISO_DATE);
		System.out.println("Date1 in string :  " + date1Str);

		// Example 2
		LocalDate date2 = LocalDate.of(2000, 01, 01);
		String date2Str = date2.format(DateTimeFormatter.ISO_DATE);
		System.out.println("Date2 in string :  " + date2Str);

		// Example 3
		LocalDate date3 = LocalDate.of(2006, 01, 01);
		String date3Str = date3.format(DateTimeFormatter.ISO_DATE);
		System.out.println("Date3 in string :  " + date3Str);
	}
}
 

Output:

Date1 in string :  2020-11-23
Date2 in string :  2000-01-01
Date3 in string :  2006-01-01
 

3.5 Example 5: Convert String To LocalDate

Use parse() method to convert String to LocalDate.

package com.javaprogramto.java8.dates.localdate;

import java.time.LocalDate;

// String to LocalDate in java 8
public class StringToLocalDateExample {

	public static void main(String[] args) {

		// Example 1
		String dateInStr = "2021-01-01";
		LocalDate date1 = LocalDate.parse(dateInStr);
		System.out.println("String to LocalDate : " + date1);

		// Example 2
		String dateInStr2 = "2025-11-30";
		LocalDate date2 = LocalDate.parse(dateInStr2);
		System.out.println("String to LocalDate : " + date2);

	}

}
 

3.6 Example 6: Convert LocalDate to LocalDateTime

Use atTime() method to convert LocalDate to LocalDateTime.

package com.javaprogramto.java8.dates.localdate;

import java.time.LocalDate;
import java.time.LocalDateTime;

public class LocalDateAtTimeExample {

	public static void main(String[] args) {
		// localdate 
		LocalDate localDate = LocalDate.now();
		
		int hour = 10;
		int minute = 20;
		int second = 30;
		
		// setting time details and converting LocalDate to LocalDateTime.
		LocalDateTime dateAndTime = localDate.atTime(hour, minute, second);
		
		System.out.println("LocalDate : "+localDate);
		System.out.println("LocalDateTime : "+dateAndTime);

	}

}
 

Output:

LocalDate : 2020-11-23
LocalDateTime : 2020-11-23T10:20:30
 


4. Conclusion

In this article, you have seen What is LocalDate class in java 8 and how to LocalDate class methods with examples.

GitHub

LocalDateCreation

AddingDaysExample

LeapYearExample

LocalDateAtTimeExample

LocalDateToStringExample

StringToLocalDateExample

Read Next:

How to convert Calendar to LocalDate ?

How to compare two dates in java 8?

How to add days to current time in java 8?

LocalDate

Tuesday, December 22, 2020

How To Convert Epoch time MilliSeconds to LocalDate and LocalDateTime in Java 8?

1. Overview

In this article, We'll learn how to convert the time from epoch milliseconds to LocalDate or LocalDateTime in java 8.

But, Converting epoch time to LocalDate or LocalDateTime can not be done directly so we need to convert first to ZonedDateTime and then next to needed type such as LocalDate or LocalDateTime.

Use Instant.ofEpochMilli(epochMilliSeconds).atZone(ZoneId.systemDefault()) method and next use either toLocalDate() or toLocalDateTime() methods.

How To Convert Epoch time MilliSeconds to LocalDate and LocalDateTime in Java 8?


2. Java 8 - Convert Epoch to LocalDate


Below is the sample program to get the LocalDate from epoch time.

In this program, first we have shown the step by step to get the required objects to get the LocalDate and finally shown the simplified the code in single line to get the same.

package com.javaprogramto.java8.dates.milliseconds;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;

/**
 * 
 * java Example to convert millisconds to LocalDate
 * 
 * @author JavaProgramTo.com
 *
 */
public class EpochMillisToLocalDate {

	public static void main(String[] args) {

		// current time in epoch format
		long epochMilliSeconds = 1608647457000l;
		
		// epoch time to Instant
		Instant instant = Instant.ofEpochMilli(epochMilliSeconds);
		
		// Instant to ZonedDateTime
		ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());
		
		// ZonedDateTime to LocalDate
		LocalDate localDate1 = zonedDateTime.toLocalDate();
		
		System.out.println("LocalDate 1 : "+localDate1);
		
		// simplified code
		LocalDate localDate2 = Instant.ofEpochMilli(epochMilliSeconds).atZone(ZoneId.systemDefault()).toLocalDate();

		System.out.println("LocalDate 2 : "+localDate2);
	}
}

Output:
LocalDate 1 : 2020-12-22
LocalDate 2 : 2020-12-22


3. Java 8 - Convert Epoch to LocalDateTime


The below example is to retrieve the LocalDateTime object from milliseconds.
package com.javaprogramto.java8.dates.milliseconds;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

/**
 * 
 * java Example to convert millisconds to LocalDateTime
 * 
 * @author JavaProgramTo.com
 *
 */
public class EpochMillisToLocalDateTime {

	public static void main(String[] args) {

		// current time in epoch format
		long epochMilliSeconds = 1608647457000l;
		
		// epoch time to Instant
		Instant instant = Instant.ofEpochMilli(epochMilliSeconds);
		
		// Instant to ZonedDateTime
		ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());
		
		// ZonedDateTime to LocalDate
		LocalDateTime localDateTime1 = zonedDateTime.toLocalDateTime();
		
		System.out.println("LocalDateTime 1 : "+localDateTime1);
		
		// simplified code
		LocalDateTime localDateTime2 = Instant.ofEpochMilli(epochMilliSeconds).atZone(ZoneId.systemDefault()).toLocalDateTime();

		System.out.println("LocalDateTime 2 : "+localDateTime2);
	}
}

Output:
LocalDateTime 1 : 2020-12-22T20:00:57
LocalDateTime 2 : 2020-12-22T20:00:57

4. Conclusion


In this article, we've seen how to do conversion epoch millis to LocalDate or LocalDateTime in java 8.




Monday, December 21, 2020

Java.lang.System.currentTimeMillis() Method Example

1. Overview

In this tutorial, We'll learn how to get the current time value in milliseconds in java

Java api provides a utility class System in java.lang package and System class has static method which can be directly invoked as System.currentTimeMillis().

Java.lang.System.currentTimeMillis() Method Example


2. Syntax

public static long currentTimeMillis()


From syntax, we can see that it returns a long value in milli seconds time unit.

The returned value is dependent on the underlying operating system. For example, some of the operating systems generates the time in tens of milliseconds.

This method returns the value that is difference between the current system time and coordinated UTC time 1970.


3. System.currentTimeMillis() Examples


The below example is on how to use System.currentTimeMillis() method.

package com.javaprogramto.java8.dates;

import java.sql.Date;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

import org.joda.time.DateTime;

/**
 * Example to get the current time in milli seconds.
 * 
 * @author JavaProgramTo.com
 *
 */
public class CurrentTimeSystemCurrentTimeMillis {

	public static void main(String[] args) {

		// calling currentTimeMillis() method
		long currentTimeMillis = System.currentTimeMillis();
		System.out.println("Current time in millies - "+currentTimeMillis);
		
		// using Date(long) constructor
		Date date = new Date(currentTimeMillis);
		System.out.println("Date : "+date);
		
		// java 8
		LocalDateTime localDateTime = Instant.ofEpochMilli(currentTimeMillis).atZone(ZoneId.systemDefault()).toLocalDateTime();
		System.out.println("Java 8 localdate time : "+localDateTime);
	}
}

Output:

Current time in millies - 1608565975991
Date : 2020-12-21
Java 8 localdate time : 2020-12-21T21:22:55.991


In the above program, First we have retrieved the current date and time in milli seconds as long value and next converted the long value into Date value.

And also converted the long value into LocalDateTime object in java 8.


4. Conclusion

In this article, We've seen how to get the current date time in milli seconds in java.

GitHub

Java 8 Date Time Examples

Tuesday, December 15, 2020

How To Get Current Date and Time in Java 8 and Older?

1. Overview

In this tutorial, We'll learn how to get the current date and time in java and new date time api in java 8.

There are different classes in java to get the current date and time and let us explore the example programs.

java.util.Date
Java 8 - java.time.Clock
java.util.Calendar
java.sql.Date
java.text.SimpleDateFormat
Java 8 - java.time.LocalDate
Java 8 - java.time.LocalTime
Java 8 - java.time.LocalDateTime
Java 8 - java.time.ZonedDateTime
Java 8 - java.time.format.DateTimeFormatter

How To Get Current Date and Time in Java 8 and Older?


2. Using java.util.Date


Use the util Date class constructor to get the current date and time values.

package com.javaprogramto.java8.dates.getdatetime;

import java.util.Date;

public class DateExample {

	public static void main(String[] args) {

		// using new Date()
		Date currentDateTime = new Date();
		System.out.println("Current date time using Date() : " + currentDateTime);

		// using System.currentTimeMillis()
		long milliSeconds = System.currentTimeMillis();
		currentDateTime = new Date(milliSeconds);
		System.out.println("Current date time using System.currentTimeMillis() : " + currentDateTime);
	}
}

Output:

Current date time using Date() : Tue Dec 15 20:47:44 IST 2020
Current date time using System.currentTimeMillis() : Tue Dec 15 20:47:44 IST 2020

3. Using java.util.Calendar


Use Calendar.getTime() method to get the Date instance.

package com.javaprogramto.java8.dates.getdatetime;

import java.util.Calendar;
import java.util.Date;

public class CalendarExample {

	public static void main(String[] args) {
		
		// Getting the calendar object
		Calendar cal = Calendar.getInstance();

		// Getting the util Date.
		Date currentDateTime = cal.getTime();
		System.out.println("Current Date Time : "+currentDateTime);
	}
}

Output:

Current Date Time : Tue Dec 15 20:51:02 IST 2020

4. Using java 8 - java.time.Clock


Use java 8 new method Instant() method from Clock class.

package com.javaprogramto.java8.dates.getdatetime;

import java.time.Clock;
import java.time.Instant;

public class ClockExample {

	public static void main(String[] args) {
		Clock clockInUTC = Clock.systemUTC();
		Instant instnat = clockInUTC.instant();
		
		System.out.println("Java 8 - Current date time : "+instnat);
	}
}

Output:


5. Using java.sql.Date


This sql Date class returns only the Date part without time units. Pass the time in milliseconds to the sql Date() constructor and returns the date.

package com.javaprogramto.java8.dates.getdatetime;

import java.sql.Date;

public class SqlDateExample {

	public static void main(String[] args) {
		
		long timeInMillis = System.currentTimeMillis();
		
		Date sqlDate = new Date(timeInMillis);
		
		System.out.println("Current date from sql date : "+sqlDate);
	}
}

Output:
Current date from sql date : 2020-12-15

6. Using java.text.SimpleDateFormat


Use SimpleDateFormat class to get the date and time in our custom desired format.

Next, call format() method with the util Date and returns date in string format.

package com.javaprogramto.java8.dates.getdatetime;

import java.text.SimpleDateFormat;
import java.util.Date;

public class SimpleDateFormatExample {

	public static void main(String[] args) {

		// current date custom format
		SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm");
		
		// current date and time
		Date currentDate = new Date();
		
		// Util Date to String using format()
		String strDate = dateFormatter.format(currentDate);

		System.out.println("Current Date using SimpleDateFormat : "+strDate);
	}
}

Output:

Current Date using SimpleDateFormat : 2020-12-15 09:20

7. Using Java 8 - java.time.LocalDate


Use LocalDate.now() method to get the current date. This method does not return the time formats and stores the only date values.

Note: If you want to get only date part in java 8 then use LocalDate class.

package com.javaprogramto.java8.dates.getdatetime;

import java.time.LocalDate;

public class LocalDateExample {
	
	public static void main(String[] args) {
		
		// using LocalDate class
		LocalDate localDateCurrentDate = LocalDate.now();
		
		// print the current date
		System.out.println("LocalDate current date : "+localDateCurrentDate);
	}
}

Output:

LocalDate current date : 2020-12-15

8. Using Java 8 - java.time.LocalTime


In java 8, LocalTime class works opposite to the LocalDate class and LocalTime.now() method gives only time part with milli seconds by default.

package com.javaprogramto.java8.dates.getdatetime;

import java.time.LocalTime;

public class LocalTimeExample {

	public static void main(String[] args) {
		
		// Using LocalTime class now() method
		LocalTime localTimeCurrentTime = LocalTime.now();
		
		// using 
		System.out.println("LocalTime : "+localTimeCurrentTime);
	}
}
Output:
LocalTime : 21:28:59.495299

9. Using Java 8 - java.time.LocalDateTime


Another class from java 8 LocalDateTime class which gives both date and time part. Use now() method to get the current date and time.

package com.javaprogramto.java8.dates.getdatetime;

import java.time.LocalDateTime;

public class LocalDateTimeExample {

	public static void main(String[] args) {
		
		// using LocalDateTime class now() method
		LocalDateTime now = LocalDateTime.now();
		
		// printing
		System.out.println("Current date time from LocalDateTime : "+now);
	}
}

Output:
Current date time from LocalDateTime : 2020-12-15T21:33:16.944571

10. Using Java 8 - java.time.ZonedDateTime


Next java 8 class is ZonedDateTime and this works with timezone part along with the date time.

Use now() method to get the current date time from the current timezone.

package com.javaprogramto.java8.dates.getdatetime;

import java.time.ZonedDateTime;

public class ZonedDateTimeExample {

	public static void main(String[] args) {

		// Using ZonedDateTime class now() method
		ZonedDateTime zonedDateTime = ZonedDateTime.now();
		
		// print current date time from ZonedDateTime class.
		System.out.println("ZonedDateTime : "+zonedDateTime);
	}
}

Output:
ZonedDateTime : 2020-12-15T21:36:12.881014+05:30[Asia/Kolkata]

11. Using Java 8 - java.time.format.DateTimeFormatter


Use DateTimeFormatter class to get the date in custom format in java 8 api.

Pass the date pattern to DateTimeFormatter.ofPattern() method and format() method to get the LocalDateTime or ZonedDateTime in string format.

package com.javaprogramto.java8.dates.getdatetime;

import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class DateTimeFormatterExamples {

	public static void main(String[] args) {
		DateTimeFormatter formatterInJava8 = DateTimeFormatter.ofPattern("yyyy/MMM/dd HH:mm:ss");
		
		LocalDateTime LocalDateTimeCurrentTime = LocalDateTime.now();
		String date1 = formatterInJava8.format(LocalDateTimeCurrentTime);

		ZonedDateTime zonedDateTime = ZonedDateTime.now();
		String date2 = formatterInJava8.format(zonedDateTime);
		
		System.out.println("Date in custom format : ");
		System.out.println("Current date time from LocalDateTime : "+date1);
		System.out.println("Current date time from ZonedDateTime : "+date2);
	}
}

Output:
Date in custom format : 
Current date time from LocalDateTime : 2020/Dec/15 21:41:17
Current date time from ZonedDateTime : 2020/Dec/15 21:41:17

12. Conclusion


In this article, we've seen various ways to get the date and time in java older versions and new java 8 api with examples.



Saturday, December 12, 2020

Java - Get Time In MilliSeconds

1. Overview

In this tutorial, We'll learn how to get the time in milliseconds in java. Time in milliseconds is the right way and format in storing into the database for date time columns. Because this is stored as Number type and which reduces the space than DateTime type in SQL.

Let us come to our topic today is getting the time milliseconds can be retrieved from Date, Calendar and java 8 api classes such Instant, ZonedDateTime classes.

Java - Get Time In MilliSeconds


2. Using java.util.Date


First, we'll try with the simple way to get the time in milliseconds format is from Date class. Date class has a method getTime() which returns the milliseconds in long value for the given time or current time.

package com.javaprogramto.java8.dates.milliseconds;

import java.util.Date;

/**
 * Example to get time in milli seconds in java using util Date api
 * 
 * @author JavaProgramTo.com
 *
 */
public class MilliSecondsFromDate {

	public static void main(String[] args) {
		
		// Getting the current date from Date class.
		Date currentDate = new Date();
		
		// Getting the time in milliseconds.
		long milliSeconds = currentDate.getTime();
		
		// printing the values
		System.out.println("Current date : "+currentDate);
		System.out.println("Current date time in milliseconds : "+milliSeconds);
		
		// Creating the future date
		Date futureDate = new Date(2025, 01, 01, 02, 30, 50);
		
		// Getting the future date
		milliSeconds = futureDate.getTime();
		
		// printing the future date time values
		System.out.println("Future date : "+futureDate);
		System.out.println("Future date time in milliseconds : "+milliSeconds);
	}
}

Output:
Current date : Sat Dec 12 21:48:25 IST 2020
Current date time in milliseconds : 1607789905027
Future date : Sun Feb 01 02:30:50 IST 3925
Future date time in milliseconds : 61696501250000

3. Using java.util.Calendar


Next, use the Calendar class to get the time in milli seconds. This class has a method getTimeInMillis() which returns the milliseconds for the time.

package com.javaprogramto.java8.dates.milliseconds;

import java.util.Calendar;
import java.util.Locale;

/**
 * Example to get time in milli seconds in java using Calendar api
 * 
 * @author JavaProgramTo.com
 *
 */
public class MilliSecondsFromCalendar {

	public static void main(String[] args) {
		
		// Getting the current date from Calendar class.
		Calendar calendar = Calendar.getInstance();
		
		// Getting the time in milliseconds.
		long milliSeconds = calendar.getTimeInMillis();
		
		// printing the values
		System.out.println("Current calender time in milliseconds : "+milliSeconds);
		
		// Creating another calendar object for Canada locale
		Calendar canadaLocale = Calendar.getInstance(Locale.CANADA);
		
		// Getting the future date
		milliSeconds = canadaLocale.getTimeInMillis();
		
		// printing the future date time values
		System.out.println("Future date time in milliseconds : "+milliSeconds);
	}
}

Output:
Current calender time in milliseconds : 1607790439838
Future date time in milliseconds : 1607790439859

4. Using Java 8 API


There are multiple ways to get the date time in milliseconds in java 8 date time api using Instant and ZonedDateTime classes.

Use toEpochMilli() method to get the date time in milli seconds epoch format.

package com.javaprogramto.java8.dates.milliseconds;

import java.time.Instant;
import java.time.ZonedDateTime;

/**
 * Example to get time in milli seconds in java 8 Using ZonedDateTime and Instant.
 * 
 * @author JavaProgramTo.com
 *
 */
public class MilliSecondsInJava8 {

	public static void main(String[] args) {
		
		// Getting milli seconds from ZonedDateTime class.
		
		// Creating zoned date time
		ZonedDateTime dateTime = ZonedDateTime.now();
		
		// getting the instant from zoned date time
		Instant instant = dateTime.toInstant();
		
		// Converting Instant time to epoch format milli seconds
		long timeInMilliSeconds = instant.toEpochMilli();
		
		// print the output
		System.out.println("Milli seconds from ZonedDateTime : "+timeInMilliSeconds);
		
		// Getting the milli seconds from Instant class.
		// Creating Instant object
		Instant instantTime = Instant.now();
		
		// Getting millis epoch value
		timeInMilliSeconds = instantTime.toEpochMilli();
		
		// printing
		System.out.println("Milli seconds from Instant : "+timeInMilliSeconds);
	}
}

Output:
Milli seconds from ZonedDateTime : 1607790957290
Milli seconds from Instant : 1607790957291

5. Conclusion


In this article, we've seen how to get the time in milli seconds in java 8 and older versions with examples.

Date class - use getTime() method
Calender class - use getTimeInMilli()
Java 8 api - use toEpochMilli()


Monday, December 7, 2020

Java Convert LocalDate to ZonedDateTime

1. Overview

In this tutorial, We'll learn how to convert the LocalDate to ZonedDateTime in java 8.

LocalDate is having only date units without timezone and ZonedDateTime object contains date, time units with timezone information. But, when we want to convert LocalDate to ZonedDateTime, we have to supply the remaining time units and timezone values and add to the LocalDate object.

This is solved using a simple method atStartOfDay() from LocalDate class with ZoneId information as an argument.

Let us explore how to convert String to ZonedDateTime and LocalDate to ZonedDateTime object.

Java Convert LocalDate to ZonedDateTime


2. Java 8 Convert String to ZonedDateTime Object


In the below example, we are taking the string as input date in format "yyyy-MM-dd" and pass to the LocalDate.parse() method and then covert it to the ZonedDateTime object.

package com.javaprogramto.java8.dates.localdate;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;

/**
 * Example to convert String to ZonedDateTime.
 * 
 * @author JavaProgramTo.com
 *
 */
public class StringToZonedDateTimeExample {

	public static void main(String[] args) {

		// date in string format
		String date = "2022-03-02";

		// Converting String to LocalDate.
		LocalDate localDate = LocalDate.parse(date);

		// Creating timezone
		ZoneId zoneid = ZoneId.systemDefault();

		// LocalDate to zoneddatetime
		ZonedDateTime zonedDateTimeFromString = localDate.atStartOfDay(zoneid);

		System.out.println("String date : " + date);
		System.out.println("ZonedDateTime : " + zonedDateTimeFromString);
	}
}
Output:

String date : 2022-03-02
ZonedDateTime : 2022-03-02T00:00+05:30[Asia/Kolkata]

3. Java 8 Convert LocalDate to ZonedDateTime Object


Next, convert the LocalDate object into ZonedDateObject with PST America timezone.

Use atStartOfDay() method with PST timezone is passed using ZoneId.of() method.

package com.javaprogramto.java8.dates.localdate;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;

/**
 * Example to convert LocalDate to ZonedDateTime with PST zone.
 * 
 * @author JavaProgramTo.com
 *
 */
public class LocalDateToZonedDateTimePSTExample {

	public static void main(String[] args) {

		// Creating LocalDate object
		LocalDate localDate = LocalDate.now();

		// Creating timezone with PST zone id. We can pass here any timezone id supported by java.
		ZoneId zoneid = ZoneId.of("US/Pacific");

		// LocalDate to PST zoneddatetime
		ZonedDateTime zonedDateTimeInPST = localDate.atStartOfDay(zoneid);

		System.out.println("localDate : " + localDate);
		System.out.println("ZonedDateTime in PST : " + zonedDateTimeInPST);
	}
}

Output:

localDate : 2020-12-07
ZonedDateTime in PST : 2020-12-07T00:00-08:00[US/Pacific]

4. Conclusion


In this article, We've seen the examples on how to convert LocalDate to ZonedDateTime in java 8 api.



Sunday, December 6, 2020

Java Convert LocalDate to LocalDateTime

1. Overview

In this tutorial, We'll learn how to convert LocalDate to LocalDateTime in java 8. LocalDate class stores only year, month and day. But, this does not store the time part and timezone. Whereas LocalDateTime holds the date and time part with naoseoncds.

You might have doubt by this time, how to convert the LocalDate to LocalDateTime because LocalDate is not having the time part but LocalDateTime does have. In order to convert localdate to localdatetime, we need to explicitly append the time part as needed.

This conversion can be done in two ways. Use atStartOfDay() or atTime() methods to append the time part to localdate and create a new LocalDateTime object.

Syntax:

public LocalDateTime atStartOfDay()

public LocalDateTime atTime(int hour, int minute)
public LocalDateTime atTime(int hour,
                            int minute,
                            int second)
public LocalDateTime atTime(int hour,
                            int minute,
                            int second,
                            int nanoOfSecond)							
public LocalDateTime atTime(LocalTime time)

Java Convert LocalDate to LocalDateTime


2. LocalDate to LocalDateTime using atStartOfDay() - Start Of Day


First we will look at atStartOfDay() method and how conversion is done into LocalDateTime with time part because this method is not taking any argument.

atStartOfDay() method combines localdate with the time of midnight to create a LocalDateTime at the start of this date.

This method returns a LocalDateTime formed from this date at the time of midnight, 00:00, at the start of this date.

package com.javaprogramto.java8.dates.localdate;

import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * 
 * Example to convert from LocalDate to LocalDateTime using atStartOfDay() method.
 * 
 * @author javaprogramto.com
 *
 */
public class LocalDateAtStartOfDayExample {

	public static void main(String[] args) {
		
		// creating localdate object
		LocalDate localDate = LocalDate.now();
		
		// Getting the LocalDateTime from LocalDate with atStartOfDay()
		LocalDateTime localDateTime = localDate.atStartOfDay();
		
		// printing the dates
		System.out.println("LocalDate : "+localDate);
		System.out.println("LocalDateTime : "+localDateTime);
	}
}

Output:
LocalDate : 2020-12-06
LocalDateTime : 2020-12-06T00:00

From the above output, we can see that Localdatetime is appended with hours and minutes as 00. That is LocalDateTime object is set to the start of LocalDate. This method is useful if you want to just convert LocalDate to LocalDateTime with time part as 0.


3. LocalDate to LocalDateTime using atTime() 


Next, Let us look at another method atTime() with time parameters. atTime() method is an overloaded method with different type of time arguments.

atTime() method combines this date with a time to create a LocalDateTime. The returned LocalDateTime object is added with the given time values.  But there is another overloaded method that returns ZonedLocalDate.

hour - the hour-of-day to use, from 0 to 23
minute - the minute-of-hour to use, from 0 to 59
second - the second-of-minute to represent, from 0 to 59

package com.javaprogramto.java8.dates.localdate;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

public class LocalDateToLocalDateTimeAtTimeExample {

	public static void main(String[] args) {
		// localdate
		LocalDate localDate = LocalDate.now();

		int hour = 10;
		int minute = 20;
		int second = 30;
		
		// setting time details and converting LocalDate to LocalDateTime. Remaining parts are set to 0.
		LocalDateTime dateAndTime1 = localDate.atTime(hour, minute);

		// this produces the output as same as atStartOfDay()
		LocalDateTime dateAndTime2 = localDate.atTime(0, 0);

		// with custom time parts
		LocalDateTime dateAndTime3 = localDate.atTime(hour, minute, second);
		
		// From LocalTime
		LocalDateTime dateAndTime4 = localDate.atTime(LocalTime.now());

		// printing the LocalDateTime values
		System.out.println("LocalDate : " + localDate);
		System.out.println("LocalDateTime with hour, minute : " + dateAndTime1);
		System.out.println("LocalDateTime with hour minute as 00 : " + dateAndTime2);
		System.out.println("LocalDateTime with hour, minute, second : " + dateAndTime3);
		System.out.println("LocalDateTime 4 with LocalTime including nano seconds : " + dateAndTime4);
	}
}

Output:

LocalDate : 2020-12-06
LocalDateTime with hour, minute : 2020-12-06T10:20
LocalDateTime with hour minute as 00 : 2020-12-06T00:00
LocalDateTime with hour, minute, second : 2020-12-06T10:20:30
LocalDateTime 4 with LocalTime including nano seconds : 2020-12-06T23:33:53.337752


4. Conclusion


In this article, we've seen how to convert LocalDate to LocalDateTime in java 8 date time api and shown the example programs in 2 ways.



Java LocalDate compareTo() Example

1. Overview

In this tutorial, We'll learn how to use compareTo() method of LocalDate class in java 8.

compareTo() method is part of new date time api. This method is used to check if the date1 is before date2 or date1 is after date 2 or date1 and date 2 are equals.

Syntax:
public int compareTo(ChronoLocalDate other)

This method takes any object that implements ChronoLocalDate interface. ChronoLocalDate interface implementations are HijrahDate, JapaneseDate, LocalDate, MinguoDate, ThaiBuddhistDate.

This method returns 0 if both the dates are equal.
This method returns positive value if “this date” is greater than the otherDate.
This method returns negative value if “this date” is less than the otherDate.

Java LocalDate compareTo() Example



2. Java 8 LocalDate.compareTo() Example


Example program on to understand the compareTo() method of LocalDate class.

package com.javaprogramto.java8.dates.localdate;

import java.time.LocalDate;

/**
 * Java 8 LocalDate.compareTo() method examples
 * 
 * @author javaprograto.com
 *
 */

public class LocalDateCompareToExample {

	public static void main(String[] args) {

		// Creating two LocalDate date objects using now() method
		LocalDate localDate1 = LocalDate.now();
		LocalDate localDate2 = LocalDate.now();

		// printing localDate1 and localDate2
		System.out.println("localDate1 : " + localDate1);
		System.out.println("localDate2 : " + localDate2);

		// calling compareTo() method on two local dates
		int compareToResult = localDate1.compareTo(localDate2);

		// LocalDate equals example
		if (compareToResult == 0) {
			System.out.println("localDate1 and localDate2 are same");
		} else if (compareToResult == 1) {
			System.out.println("localDate1 is after localDate2 ");
		} else {
			System.out.println("localDate1 is before localDate2 ");
		}

		// Creating another two LocalDate date objects using of() method with different
		// dates
		LocalDate localDate3 = LocalDate.of(2025, 01, 01);
		LocalDate localDate4 = LocalDate.of(2030, 01, 01);

		// printing localDate3 and localDate4
		System.out.println("\nlocalDate3 : " + localDate3);
		System.out.println("localDate4 : " + localDate4);

		// calling compareTo() method on two local dates
		compareToResult = localDate3.compareTo(localDate4);

		// LocalDate equals example
		if (compareToResult == 0) {
			System.out.println("localDate3 and localDate4 are same");
		} else if (compareToResult == 1) {
			System.out.println("localDate3 is after localDate4 ");
		} else {
			System.out.println("localDate3 is before localDate4 ");
		}
	}
}
Output:
localDate1 : 2020-12-06
localDate2 : 2020-12-06
localDate1 and localDate2 are same

localDate3 : 2025-01-01
localDate4 : 2030-01-01
localDate3 is before localDate4 

3. compareTo() method with different Date Time Type Objects


In the previous example compared two LocalDate objects with same and different values.

Now, compare LocalDate with MinguoDate objects using compareTo() objects.

package com.javaprogramto.java8.dates.localdate;

import java.time.LocalDate;
import java.time.chrono.MinguoDate;

/**
 * Java 8 LocalDate.compareTo() method examples with MinguoDate
 * 
 * @author javaprograto.com
 *
 */

public class LocalDateCompareToWithMinguoDate {

	public static void main(String[] args) {

		// Creating LocalDate date objects using now() method
		LocalDate localDate = LocalDate.now();
		
		// Creating MinguoDate date objects using now() method
		MinguoDate minguoDate = MinguoDate.now();

		// printing localDate and minguoDate
		System.out.println("localDate : " + localDate);
		System.out.println("minguoDate : " + minguoDate);

		// calling compareTo() method on two local dates
		int compareToResult = localDate.compareTo(minguoDate);

		// Printing output of compareTo() method
		System.out.println("compareToResult : "+compareToResult);
		
		// LocalDate equals example
		if (compareToResult == 0) {
			System.out.println("localDate and minguoDate are same");
		} else if (compareToResult > 0) {
			System.out.println("localDate is after minguoDate ");
		} else {
			System.out.println("localDate is before minguoDate ");
		}
	}
}
Output:
localDate : 2020-12-06
minguoDate : Minguo ROC 109-12-06
compareToResult : -4
localDate is before minguoDate 

From the above example, we have passed the MinguoDate object to the compareTo() method and returned negative value. localdate value is before minguo date.

LocalDate.compareTo() method works with the different type of date objects and sub implementation of ChronoLocalDate interface only example with MinguoDate.


4. Conclusion


In this article, we've seen the usage of compareTo() method of LocalDate class with passing the arguments LocalDate and MinguoDate.


Java LocalDate equals() Example

1. Overview

In this tutorial, We'll learn how to compare two dates in java 8 using LocalDate.equals() method. equals() method returns a boolean value if the dates are same , it returns true else false.

Syntax:
public boolean equals(Object obj)

equals() method compares two dates contents in detail with year, month and day values. If any one of these values are not matched then it consider as these two dates are not equal. 
This method takes Object type argument. This object type should be LocalDate and then only these objects are compared otherwise it returns false directly.

Java LocalDate – equals() Example


2. Java 8 LocalDate.equals() Example


Example program to compare two LocalDate objects in java 8 with the help of equals() method.

Read the inline comments in the below program for better understanding.

package com.javaprogramto.java8.dates.localdate;

import java.time.LocalDate;

/**
 * Java 8 LocalDate.equals() method examples
 * 
 * @author javaprograto.com
 *
 */

public class LocalDateEqualsExample {

	public static void main(String[] args) {

		// Creating two LocalDate date objects using now() method
		LocalDate localDate1 = LocalDate.now();
		LocalDate localDate2 = LocalDate.now();

		// printing localDate1 and localDate2
		System.out.println("localDate1 : " + localDate1);
		System.out.println("localDate2 : " + localDate2);

		// LocalDate equals example
		if (localDate1.equals(localDate2)) {
			System.out.println("localDate1 and localDate2 are same");
		} else {
			System.out.println("localDate1 and localDate2 are not same");
		}

		// Creating another two LocalDate date objects using of() method with different dates
		LocalDate localDate3 = LocalDate.of(2025, 01, 01);
		LocalDate localDate4 = LocalDate.of(2030, 01, 01);

		// printing localDate3 and localDate4
		System.out.println("\nlocalDate3 : " + localDate3);
		System.out.println("localDate4 : " + localDate4);

		// LocalDate equals example
		if (localDate3.equals(localDate4)) {
			System.out.println("localDate3 and localDate24 are same");
		} else {
			System.out.println("localDate3 and localDate4 are not same");
		}
	}
}

Output:
localDate1 : 2020-12-06
localDate2 : 2020-12-06
localDate1 and localDate2 are same

localDate3 : 2025-01-01
localDate4 : 2030-01-01
localDate3 and localDate4 are not same

3. Conclusion


In this article, we've seen how to use equals() method of LocalDate class in new datetime api in java 8 with example programs.

If we pass the LocalDateTime object to this equals() method then it returns false because internal implementation checks the given instance is type of LocalDate. If we pass LocalDateTime object, instance type check becomes false.

Alternative to this method, We can use the LocalDate.compareTo() method which compares the dates but compareTo() returns integer value rather than boolean.



Friday, December 4, 2020

Converting Between LocalDate and SQL Date In Java 8

1. Overview

In this tutorial, We'll learn how to convert java.time.LocalDate to java.sql Date in java 8 and vice versa.

This is simple to do but when working jpa framework it is bit different to deal with the table column type.

First look at the simple conversions between LocalDate and sql Date objects in java. Next, look at the JPA problem.

Converting Between LocalDate and SQL Date In Java 8


2. Direction conversion between LocalDate and SQL Date


2.1 Convert LocalDate to SQL Date


Use direct method from sql Date.valueOf() method which takes the LocalDate object. So, We can pass the object of LocalDate.now() or LocalDate.of() method.

Look at the below example.
package com.javaprogramto.java8.dates.conversion.sql;

import java.sql.Date;
import java.time.LocalDate;

public class LocalDateToSQLDateExample {

	public static void main(String[] args) {

		// creating current local date using now() method and which will return the
		// curren date.
		LocalDate currentDate = LocalDate.now();

		// LocalDate to SQL date using valueOf() method.
		Date sqlDate = Date.valueOf(currentDate);

		// printing
		System.out.println("With current local date");
		System.out.println("LocalDate : " + currentDate);
		System.out.println("SQL Date : " + sqlDate);
		
		// working with different dates.
		LocalDate pastDate = LocalDate.of(1990, 01, 01);
		LocalDate futureDate = LocalDate.of(2050, 01, 01);
		
		// converting Local dates to sql dates
		Date pastSqlDate = Date.valueOf(pastDate);
		Date futureSqlDate = Date.valueOf(futureDate);
		
		System.out.println("\nWith different local dates");
		System.out.println("Past LocalDate : " + pastDate);
		System.out.println("Past SQL Date : " + pastSqlDate);
		
		System.out.println("Future LocalDate : " + futureDate);
		System.out.println("Future SQL Date : " + futureSqlDate);
	}
}
Output:
With current local date
LocalDate : 2020-12-04
SQL Date : 2020-12-04

With different local dates
Past LocalDate : 1990-01-01
Past SQL Date : 1990-01-01
Future LocalDate : 2050-01-01
Future SQL Date : 2050-01-01

If null value is passed to the Date.valueOf() method, it will throw NullPointerException.
LocalDate nullLocalDate = null;
Date nullDate = Date.valueOf(nullLocalDate);

Output:
Exception in thread "main" java.lang.NullPointerException
	at java.sql/java.sql.Date.valueOf(Date.java:291)
	at com.javaprogramto.java8.dates.conversion.sql.LocalDateToSQLDateExample.main(LocalDateToSQLDateExample.java:38)


2.2 Convert SQL Date to LocalDate


Use toLocalDate() method to convert sql date to time LocalDate in java 8.
package com.javaprogramto.java8.dates.conversion.sql;

import java.sql.Date;
import java.time.LocalDate;

public class SQLDateToLocalDateExample {

	public static void main(String[] args) {

		// Creating sql date
		Date sqlDate = Date.valueOf("2020-12-31");
		
		// converting sql date to localdate using toLocalDate() method.
		LocalDate localDate1 = sqlDate.toLocalDate();

		// printing the local date.
		System.out.println("Local Date 1 : "+localDate1);
	}
}

Output:
Local Date 1 : 2020-12-31

3. JPA Problem Solving AttributeConverter


If you are using the LocalDate as column type in the JPA entity and this is should be having some mapping to the the database columns type. For this type, we assume that sql Date is the right one for the column type. But, database can not recognize the type LocalDate and JPA will map this to blob type rather than java sql Date object.

This is the problem now. To solve this, we should tell to JPA that if there is any column with LocalDate type, convert it into java.sql.Date when inserting into database and convert sql date to LocalDate while retrieving the records from database.

Java persistence api is added with AttributeConverter interface in jdk 1.7.

We need to implement AttributeConverter interface and need to specify the input object type and converted result object type.

This interface has two abstract methods convertToDatabaseColumn() and convertToEntityAttribute().

convertToDatabaseColumn() is to convert the LocalDate to sql date and saves into database.
convertToEntityAttribute() method is executed when fetching the records from database and converts into LocalDate.

We have used Optional inside these two methods to better handle null references to avoid null pointer exception.
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.sql.Date;
import java.time.LocalDate;
import java.util.Optional;

@Converter(autoApply = true)
public class LocalDateConverterExample implements AttributeConverter<LocalDate, Date> {


	// converts LocalDate to sql date using valueOf() method
    @Override
    public Date convertToDatabaseColumn(LocalDate localDate) {
        return Optional.ofNullable(localDate)
          .map(Date::valueOf)
          .orElse(null);
    }

	// converts sql date to LocalDate using toLocalDate() method
    @Override
    public LocalDate convertToEntityAttribute(Date date) {
        return Optional.ofNullable(date)
          .map(Date::toLocalDate)
          .orElse(null);
    }
}


Observe the above code, We've used the @Converter annotation with element autoApply to true. That means apply this conversion is applied to all targeted types by the persistence provider.

But by default this property autoApply is set to false.

If there is more than one converter defined for the same target type, the Convert annotation should be used to explicitly specify which converter to use.

4. Conclusion


In this article, We've seen how to convert between LocalDate and SQL Date in java with example programs.

And also shown how to solve the LocalDate type problem in JPA framework using AttributeConverter interface and @Converter annotation.



Thursday, December 3, 2020

Java LocalDate adjustInto() Examples

1. Overview

In this article, We'll learn how to use LocalDate class adjustInto() method in java 8.

This adjustInto(Temporal temporal) method adjusts the value of temporal object as same as the this or current object.

Let us take a simple example, We have two objects of LocalDate class objects localDate1 and localDate2. If we call the adjustInto() method like this localDate1.adjustInto(localDate2) then localDate2 value will be modified to as same as localDate1. After this line execution, both of these objects would be having the same values.

Read more about LocalDate Class

Java LocalDate adjustInto() Examples


2. LocalDate adjustInto() syntax

adjustInto() method modifies the values of passed date object to the called object. In other words it creates a copy of same this object.

Syntax:

Temporal adjustInto(Temporal temporal)


adjustInto() method returns the modified new object but the passed object can not be changed because LocalDate is immutable class.

Temporal is an interface and is implemented by all these classes HijrahDate, Instant, JapaneseDate, LocalDate, LocalDateTime, LocalTime, MinguoDate, OffsetDateTime, OffsetTime, ThaiBuddhistDate, Year, YearMonth, ZonedDateTime

So that means we can pass any date class object to this method.


3. Java 8 LocalDate adjustInto() Examples

In the below example, we have taken simple two LocalDate objects such as localDate1 and localDate2.

Next, called localDate2.adjustInfo(localDate2) which returns the new object as same as localDate2.

We need to typecast to right object otherwise will get the compile time error.

In our case object is LocalDate and type casted to correct class.

package com.javaprogramto.java8.dates.localdate;

import java.time.LocalDate;

/**
 * 
 * LocalDate.adjustInfo() example in java 8
 * 
 * @author javaprogramto.com
 *
 */
public class LocalDateAdjustIntoExample {

	public static void main(String[] args) {

		LocalDate localDate1 = LocalDate.now();
		LocalDate localDate2 = LocalDate.of(2020, 01, 02);

		System.out.println("Before");
		System.out.println("LocalDate 1 : " + localDate1);
		System.out.println("LocalDate 2 : " + localDate2);

		localDate1 = (LocalDate) localDate2.adjustInto(localDate1);

		System.out.println("After");
		System.out.println("LocalDate 1 : " + localDate1);
		System.out.println("LocalDate 2 : " + localDate2);
	}
}

Output:

Before
LocalDate 1 : 2020-12-03
LocalDate 2 : 2020-01-02
After
LocalDate 1 : 2020-01-02
LocalDate 2 : 2020-01-02

From the output, we can observe that localDate1 value is changed to localDate2.


4. Another Example To adjustInto() with ZonedDateTime Examples

In the below example, created three objects using ZonedDateTime, LocalDateTime and LocalDateTime.

Now, we will adjust first two dates values using adjustInto() method.


package com.javaprogramto.java8.dates.localdate;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZonedDateTime;

/**
 * 
 * LocalDate.adjustInfo() example in java 8 with different Temporal types.
 * 
 * @author javaprogramto.com
 *
 */
public class LocalDateAdjustIntoExample {

	public static void main(String[] args) {

		// created 3 datetime objects using different temporal objects such as ZonedDateTime, LocalDateTime
		ZonedDateTime date1 = ZonedDateTime.now();
		LocalDateTime date2 = LocalDateTime.now();
		LocalDateTime date3 = LocalDateTime.of(LocalDate.now(), LocalTime.now());

		System.out.println("Before");
		System.out.println("date1 : " + date1);
		System.out.println("date2 : " + date2);
		System.out.println("date3 : " + date3);

		// adjusting the date1 and date2 values using adjustInto() method.
		date1 = (ZonedDateTime) date3.adjustInto(date1);
		date2 = (LocalDateTime) date3.adjustInto(date2);

		System.out.println("After");
		System.out.println("date1 : " + date1);
		System.out.println("date2 : " + date2);
		System.out.println("date3 : " + date3);
	}
}

Output:

Before
date1 : 2020-12-03T23:42:00.360295+05:30[Asia/Kolkata]
date2 : 2020-12-03T23:42:00.360445
date3 : 2020-12-03T23:42:00.360565
After
date1 : 2020-12-03T23:42:00.360565+05:30[Asia/Kolkata]
date2 : 2020-12-03T23:42:00.360565
date3 : 2020-12-03T23:42:00.360565

Observe the output after date1 and date2 adjustment and those two dates milliseconds are changed to date3 milliseconds. Hence, all three dates are having the same values.

adjustInto() method can be also used to copy the current date object into another object (creating the duplicate date and time objects).

if the method not invoked with the proper date objects then it may throw the following runtime exceptions.

DateTimeException - if unable to make the adjustment

ArithmeticException - if numeric overflow occurs

5. Conclusion

In this article, we've seen how to use the LocalDate.adjustInto() method with examples in java 8 api.

GitHub

Convert Calendar to LocalDate in java 8

Java – Convert LocalDate to Date

1. Overview

In this tutorial, We'll learn how to convert Java 8 LocalDate to util Date. Before jumping into the example programs let us understand the core difference between Date and LocalDate classes.

Date - java.util.Date - date + time + timezone
LocalDate - java.time.Localdate - date only

Java util date store the date and time but does not store the timezone. When we print the timezone it just takes the system timezone where as LocalDate is added in java 8 api and it stores the only date part without time part.

Java – Convert LocalDate to Date


2. Convert LocalDate To Date in Java

Understand the steps needed to write the code

Steps:

Step 1: First Create the LocalDate object using either now() or of() method. now() method gets the current date where as of() creates the LocalDate object with the given year, month and day.

Step 2: Next, Get the timezone from operating system using ZoneId.systemDefault() method.

Step 3: Additionally, Call LocalDate.atStartOfDay() method with timezone as parameter and it returns ZonedDateTime.

Step 4: Finally, Call Date.from(zonedDateTime.toInstant()) method and pass the Instant object from zoned date time.toInstant() method. This from() method returns the util Date object.

package com.javaprogramto.java8.dates.conversion.dateto;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;

/**
 * Example to convert java.time.LocalDate to java.util.Date.
 * 
 * @author javaprogramto.com
 */
public class LocalDateToDateExample {

	public static void main(String[] args) {

		// Creating the LocalDatetime object
		LocalDate currentLocalDate = LocalDate.now();
		
		// Getting system timezone
		ZoneId systemTimeZone = ZoneId.systemDefault();
		
		// converting LocalDateTime to ZonedDateTime with the system timezone
		ZonedDateTime zonedDateTime = currentLocalDate.atStartOfDay(systemTimeZone);
		
		// converting ZonedDateTime to Date using Date.from() and ZonedDateTime.toInstant()
		Date utilDate = Date.from(zonedDateTime.toInstant());
		
		// Printing the input and output dates
		System.out.println("LocalDate  : "+currentLocalDate);
		System.out.println("Util Date : "+utilDate);

	}
}

Output:

LocalDate  : 2020-12-03
Util Date : Thu Dec 03 00:00:00 IST 2020


3. Conclusion

In this article, We've seen converting the LocalDate to Date in java 8 with example program.

GitHub