Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Monday, November 23, 2020

How To Convert String to Date in Java 8

1. Overview


In this article, you'll be learning how to convert String to Date in Java 8 as well as with Java 8 new DateTime API.

String date conversion can be done by calling the parse() method of LocalDate, DateFormat and SimpleDateFormat classes.

LocalDate is introduced in java 8 enhancements.

DateFormat is an abstract class and direct subclass is SimpleDateFormat.

To convert a String to Date, first need to create the SimpleDateFormat or LocalDate object with the data format and next call parse() method to produce the date object with the contents of string date.

Java Convert String to Date (Java 8 LocalDate.parse() Examples)


First, let us write examples on string to date conversations with SimpleDateFormat classs and then next with DateFormat class.

At last, Finally with LocalDate class parse() method.

All of the following classes are used to define the date format of input string. Simply to create the date formats.

LocalDate
DateFormat
SimpleDateFormat

Note: In date format Captial M indicates month whereas lowercase m indicate minutes.

This will be asked in the interview or written test on How to Format Date to String in Java 8?

2. How To Convert String To Date yyyy-MM-dd - SimpleDateFormat


The input string can be any format but all should be valid date formats.

So, First need to pass the date format of string to SimpleDateFormat class and then call parse() method of it. This method returns the String date in Date object format.

See the below example.

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

public class SimpleFormatStringToDateExample1 {

	public static void main(String[] args) throws ParseException {
		
		
		String string = "2020-01-01";
		
		System.out.println("Original string (that holds date value) : "+string);
		
		SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
		
		Date dateObject = dateFormatter.parse(string);
		
		System.out.println("Converted Date value : "+dateObject);

	}

}

Output:

Original string (that holds date value) : 2020-01-01
Converted Date value : Wed Jan 01 00:00:00 IST 2020

If the date format is not matched to the string value then it throws ParseException.

Original string (that holds date value) : 2020-01-01
Exception in thread "main" java.text.ParseException: Unparseable date: "2020-01-01"
	at java.text.DateFormat.parse(DateFormat.java:366)
	at SimpleFormatStringToDateExample.main(SimpleFormatStringToDateExample.java:16)

3. How to convert string to date in java in dd-MM-yyyy format


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

public class SimpleFormatStringToDateExample2 {

	public static void main(String[] args) throws ParseException {
		
		
		String string = "01-01-2020";
		
		System.out.println("Original string (that holds date value) dd-MM-yyyy : "+string);
		
		SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM-yyyy");
		
		Date dateObject = dateFormatter.parse(string);
		
		System.out.println("Converted Date value : "+dateObject);

	}

}
Output:
Original string (that holds date value) dd-MM-yyyy : 01-01-2020
Converted Date value : Wed Jan 01 00:00:00 IST 2020

4. How to format the String to Date? Examples on multiple date formats


Below program shows on string date in various formats that converts to the Date object with SimpleDateFormat class parse() method.

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

public class MultipleFormatsStringToDateExample {

	public static void main(String[] args) throws ParseException {

		// string dates
		String stringDate1 = "31/01/2020";
		String stringDate2 = "31-Jan-2020";
		String stringDate3 = "12 31, 2020";
		String stringDate4 = "Thu, Jan 31 2020";
		String stringDate5 = "Thu, Jan 31 2020 23:37:50";
		String stringDate6 = "31-Jan-2020 23:37:50";
		
		// formatters
		SimpleDateFormat formatter1 = new SimpleDateFormat("dd/MM/yyyy");
		SimpleDateFormat formatter2 = new SimpleDateFormat("dd-MMM-yyyy");
		SimpleDateFormat formatter3 = new SimpleDateFormat("MM dd, yyyy");
		SimpleDateFormat formatter4 = new SimpleDateFormat("E, MMM dd yyyy");
		SimpleDateFormat formatter5 = new SimpleDateFormat("E, MMM dd yyyy HH:mm:ss");
		SimpleDateFormat formatter6 = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
		
		// conversions
		Date date1 = formatter1.parse(stringDate1);
		Date date2 = formatter2.parse(stringDate2);
		Date date3 = formatter3.parse(stringDate3);
		Date date4 = formatter4.parse(stringDate4);
		Date date5 = formatter5.parse(stringDate5);
		Date date6 = formatter6.parse(stringDate6);
		
		System.out.println("String   -   Date values");
		System.out.println(stringDate1 + " - " + date1);
		System.out.println(stringDate2 + " - " + date2);
		System.out.println(stringDate3 + " - " + date3);
		System.out.println(stringDate4 + " - " + date4);
		System.out.println(stringDate5 + " - " + date5);
		System.out.println(stringDate6 + " - " + date6);

	}

}
Output:

String   -   Date values
31/01/2020 - Fri Jan 31 00:00:00 IST 2020
31-Jan-2020 - Fri Jan 31 00:00:00 IST 2020
12 31, 2020 - Thu Dec 31 00:00:00 IST 2020
Thu, Jan 31 2020 - Fri Jan 31 00:00:00 IST 2020
Thu, Jan 31 2020 23:37:50 - Fri Jan 31 23:37:50 IST 2020
31-Jan-2020 23:37:50 - Fri Jan 31 23:37:50 IST 2020

6. How to convert string to date in Java 8 with LocalDate Predefined Formatters


Java 8 api DateTimeFormatter class is added with a set of predefined formatters which are frequently used by the developers and those are the industry standards.

This class helps to get the right formatters. Next pass the string date, formatter to LocalDate.parse() method which returns the date object.

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class StringToDateExampleWithLocalDateWithPredefinedFormatters {

	public static void main(String[] args) throws ParseException {

		// string dates
		String isoDateInString = "2020-07-20";
		
		DateTimeFormatter iso_date = DateTimeFormatter.ISO_DATE;
		
		LocalDate date = LocalDate.parse(isoDateInString, iso_date);
		
		System.out.println("Locale Date : "+date);
		
	}

}
Output:

Locale Date : 2020-07-20
LocalDate.parse() method does the conversion the given string with the given formatter. Here, used ISO_DATE date formater which produces the date as "2020-07-20".

If the formatter is not matching to the string value then it throws the runtime exception. Change the formatter different as below.
DateTimeFormatter iso_date = DateTimeFormatter.BASIC_ISO_DATE;
Error:

Exception in thread "main" java.time.format.DateTimeParseException: Text '2020-07-20' could not be parsed at index 4
	at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
	at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
	at java.time.LocalDate.parse(LocalDate.java:400)
	at StringToDateExampleWithLocalDateWithPredefinedFormatters.main(StringToDateExampleWithLocalDateWithPredefinedFormatters.java:17)

7. How to convert string to date in Java 8 with LocalDate Custom Formatters


Now we are getting the date in the different format as "May 30, 2020" but for this, there is no predefined formatter. So now, How to convert the string to date object.


Let us use the DateTimeFormatter.ofPattern() method and pass the custom pattern as "MMM dd, yyyy".

See the simple program to string date conversion:

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

public class StringToDateExampleWithLocalDateWithCustomFormatters {

	public static void main(String[] args) throws ParseException {

		// string dates
		String isoDateInString = "May 30, 2020";
		
		// custom formatter
		DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("MMM d, yyyy");
		
		// string to date conversion in java 8
		LocalDate date = LocalDate.parse(isoDateInString, customFormatter);
		
		// printing the date object
		System.out.println("Locale Date : "+date);
		
	}

}
Output:
Locale Date : 2020-05-30

8. Java 8 DateTimeFormatter VS SimpleDateFormat


A simple program that shows the differences between DateTimeFormatter VS SimpleDateFormat.

Java 8 api returns the LocalDate object as exact same as string content but SimpleDateFormat produces the Date objet which shows the full date with seconds by default even though time information is not provided.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class StringToDateExampleWithLocalDateWithCustomFormatters {

	public static void main(String[] args) throws ParseException {

		// string dates
		String isoDateInString = "May 30, 2020";
		
		// Java 8 DateTimeFormatter 
		// custom formatter
		DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("MMM d, yyyy");
		
		// string to date conversion in java 8
		LocalDate date = LocalDate.parse(isoDateInString, customFormatter);
		
		// printing the date object
		System.out.println("Java 8 DateTimeFormatter "+date);
		
		
		// Before java 8 - SimpleDateFormat
		
		SimpleDateFormat simpleCustomFormatter = new SimpleDateFormat("MMM d, yyyy");
		
		Date simpleDate = simpleCustomFormatter.parse(isoDateInString);
		
		System.out.println("SimpleDateFomat : "+simpleDate);
		
	}

}
Output:

Java 8 DateTimeFormatter 2020-05-30
SimpleDateFomat : Sat May 30 00:00:00 IST 2020

8. Conclusion


In this article, you've seen how to convert the String into Date using SimpleDateFormat.parse() and LocalDate.parse() method in Java 8.

Examples on various date formats to convert string to date.

And also Example programs on Java 8 predefined formats and how to use the custom date formats in java 8.

Finally, Differences between Java 8 DateTimeFormatter VS SimpleDateFormat.

As usual, all programs are over GitHub.


Read Next


No comments:

Post a Comment

Please do not add any spam links in the comments section.