How To Convert LocalDate to java.sql.Date In Java | Java 8 Examples | Java Inspires



 Hi Guys,

Welcome to Java Inspires..

In this post, we will see how to convert LocalDate object into java.sql.Date object.

About LocalDate :

LocalDate is an immutable date-time object that represents a date, often viewed as year-month-day. Other date fields, such as day-of-year, day-of-week and week-of-year, can also be accessed. For example, the value "2nd October 2007" can be stored in a LocalDate.

This class does not store or represent a time or time-zone. Instead, it is a description of the date, as used for birthdays. It cannot represent an instant on the time-line without additional information such as an offset or time-zone.

The ISO-8601 calendar system is the modern civil calendar system used today in most of the world. It is equivalent to the proleptic Gregorian calendar system, in which today's rules for leap years are applied for all time. For most applications written today, the ISO-8601 rules are entirely suitable. However, any application that makes use of historical dates, and requires them to be accurate will find the ISO-8601 approach unsuitable.

This is a value-based class; use of identity-sensitive operations (including reference equality (==), identity hash code, or synchronization) on instances of LocalDate may have unpredictable results and should be avoided. The equals method should be used for comparisons.

Java8Example.java

package com.javainspires.java8example;

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

/**
 * 
 * @author Java Inspires
 *
 */
public class Java8Example {

	public static void main(String[] args) {

		// create localdate object
		LocalDate localDate = LocalDate.now();
		// print localDate
		System.out.println("LocalDate -> " + localDate);

		// declare sql Date
		Date sqlDate = null;
		// Use Date.valueOf from sql Date class
		sqlDate = Date.valueOf(localDate);
		// print sqlDate
		System.out.println("SQL Date ->" + sqlDate);
	}
}

Run above progra as java application.
Output :

LocalDate -> 2021-01-27
SQL Date ->2021-01-27

Thank You


Post a Comment

Previous Post Next Post