Thursday, 17 August 2017

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 it to date 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.

Using SimpleDateFormat

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 you use the format method where as to convert from String to Date you will have to use parse method.

Steps to follow

  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.

Example code

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.

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 another format. In that case also first convert the String to date and then again to String in another format.

Example code

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

Using DateFormatter of new Java date time API – Java 8

If you are using Java 8 then you do have better option to convert String to date. 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.

Example code

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.

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!


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 find last modified date of a file in Java
  4. How to read file from the last line in Java

You may also like -

>>>Go to Java Programs page

No comments:

Post a Comment