Monday, August 15, 2022

How to Convert String to Date in Java

When you are displaying date you will convert date to String in required format and print it. But you may need to convert String to date in Java again if-

  1. You have to do any date calculation.
  2. You want to convert date from one format to another. In that case you do need to first convert String date to a date using the same pattern as is used for string and then convert the date again to String in another format.

In this post we'll see the options available to convert String to java.util.Date in Java using both SimpleDateFormat class and using DateTimeFormatter class Java 8 onward.


Using SimpleDateFormat for conversion

Before Java 8, a tried and tested way to convert String to java.util.Date is to use SimpleDateFormat which also gives you an option to provide customized format. For converting Date to String using SimpleDateFormat class you use the format() method where as to convert from String to Date in Java you will have to use parse() method of the SimpleDateFormat class.

Steps to follow

Steps you need to follow for converting string to date in java using SimpleDateFormat are as follows.

  1. Once you have a date String in a given format you need to create an object of SimpleDateFormat passing pattern as argument which should be similar to the pattern used in the date String.

  2. Call parse method passing date string as an argument which returns the parsed date.

SimpleDateFormat Example

Let’s see some examples using date strings with different patterns.

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

public class StringToDate {
 public static void main(String[] args) {
  
  String strDate = "30/06/2017";
  getDate(strDate, "dd/MM/yyyy");
  
  strDate = "Sun, May 8, '16";
  getDate(strDate, "EEE, MMM d, ''yy");
  
  strDate = "Sunday, May 08, 2016";
  getDate(strDate, "EEEE, MMMM dd, yyyy");
  
  strDate = "2016-05-08 AD at 10:13:46 IST";
  getDate(strDate, "yyyy-MM-dd G 'at' hh:mm:ss z");
  
  strDate = "2017-08-12T20:17:46.384Z";
  strDate = strDate.replaceAll("Z", "+0530");
  getDate(strDate, "yyyy-MM-dd'T'hh:mm:ss.SSSZ");
  
 }
 
 private static void getDate(String strDate, String pattern){
  SimpleDateFormat formatter = new SimpleDateFormat(pattern);
  try {
   Date date = formatter.parse(strDate);
   System.out.println("Parsed date " + date);
  } catch (ParseException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

Output

Parsed date Fri Jun 30 00:00:00 IST 2017
Parsed date Sun May 08 00:00:00 IST 2016
Parsed date Sun May 08 00:00:00 IST 2016
Parsed date Sun May 08 10:13:46 IST 2016
Parsed date Sat Aug 12 20:17:46 IST 2017

Here note that for the date strDate = "2017-08-12T20:17:46.384Z"; where 'Z' literal is used with the date, you need to remove that literal, it won’t be parsed otherwise and throw exception as follows–

java.text.ParseException: Unparseable date: "2017-08-12T20:17:46.384Z"
 at java.text.DateFormat.parse(Unknown Source)
 at org.netjs.prgrm.StringToDate.getDate(StringToDate.java:31)
 at org.netjs.prgrm.StringToDate.main(StringToDate.java:24)

Here, while replacing it, I have replaced it with the difference with the GMT time i.e. 5 Hrs. 30 Mins (For India). You can replace it with the time zone offset of your requirement or you can find that difference from GMT programmatically.

Using DateTimeFormatter class in Java 8 Date&Time API

If you are using new Java date time API (Java 8 onward) then you do have better options to convert String to date in Java. If you have an object of type LocalDate, LocalTime or LocalDateTime you can format it using the parse() method.

There are two overloaded parse methods:

  • parse(CharSequence text)– Here text argument denotes the date string that has to be parsed. This parse method uses standard ISO_LOCAL_DATE formatter.
  • parse(CharSequence text, DateTimeFormatter formatter)– In this variant of parse method you can pass custom formatter.

DateTimeFormatter Java Example for Converting String to Date

Let’s see some examples with different formats.

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

public class String2Date {

 public static void main(String[] args) {
  try{
   String strDate = "2011-12-03T10:15:30";
   LocalDateTime localDateTime = LocalDateTime.parse(strDate);
   System.out.println("date " + localDateTime);
   
   strDate = "30/06/2017";
   LocalDate localDate = LocalDate.parse(strDate, DateTimeFormatter.ofPattern("dd/MM/yyyy"));
   System.out.println("date " + localDate);
   
   strDate = "Sun, May 8, '16";
   localDate = LocalDate.parse(strDate, DateTimeFormatter.ofPattern("EEE, MMM d, ''yy"));
   System.out.println("date " + localDate);
   
   strDate = "2017-08-12T20:17:46.384Z";
   localDateTime = LocalDateTime.parse(strDate, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSz"));
   System.out.println("date " + localDateTime);
   
   strDate = "2016-05-08 AD at 10:13:46 IST";
   localDateTime = LocalDateTime.parse(strDate, DateTimeFormatter.ofPattern("yyyy-MM-dd G 'at' HH:mm:ss z"));
   System.out.println("date " + localDateTime);
   
   strDate = "2017-08-15 03:32:12-0400";  
   ZonedDateTime zonedDateTime = ZonedDateTime.parse(strDate, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssxx"));
   System.out.println("date " + zonedDateTime);
  }catch(DateTimeParseException ex){
   ex.printStackTrace();
  }
 }
}

Output

date 2011-12-03T10:15:30
date 2017-06-30
date 2016-05-08
date 2017-08-12T20:17:46.384
date 2016-05-08T10:13:46
date 2017-08-15T03:32:12-04:00

Here note that, for the date time with zone offset strDate = "2017-08-15 03:32:12-0400"; ZonedDateTime is used to correctly parse the string.

Converting from one String date format to another

It may happen that you get the date in String format and you have to convert it in another format. In that case also first convert the String to date in Java and then again to String in another format.

Suppose you get the String date in the format dd/MM/yyyy which you will have to convert to format yyyy-MM-dd.

public class StringToDate {
 public static void main(String[] args) {
  
  String strDate = "30/06/2017";
  System.out.println("date in old format - " + strDate);
  SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
  try {
   Date date = formatter.parse(strDate);
   System.out.println("Parsed date - " + date);
   
   formatter = new SimpleDateFormat("yyyy-MM-dd");
   System.out.println("date in new format - " + formatter.format(date));
  } catch (ParseException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } 
 }
}

Output

date in old format - 30/06/2017
Parsed date - Fri Jun 30 00:00:00 IST 2017
date in new format - 2017-06-30

That's all for this topic How to Convert String to Date in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. How to Convert Date to String in Java
  2. How to Convert Date And Time Between Different Time-Zones in Java
  3. How to Display Time in AM-PM Format in Java
  4. Difference Between Two Dates in Java
  5. How to Find Last Modified Date of a File in Java

You may also like-

  1. Java Program to Find The Longest Palindrome in a Given String
  2. Find All Permutations of a Given String Java Program
  3. Creating Tar File And GZipping Multiple Files in Java
  4. Print Odd-Even Numbers Using Threads And wait-notify Java Program
  5. How HashMap Works Internally in Java
  6. Reflection in Java - Getting Field Information
  7. Java Stream API Examples
  8. throw Statement in Java Exception Handling

No comments:

Post a Comment