How to convert String to Date in Java

In this tutorial, we will see how to convert a String into Date in Java, for many developers this is still a challenge so we try to help in making it simple.

// String -> Date
   SimpleDateFormat.parse(String);

// Date -> String
   SimpleDateFormat.format(date);

// In Java 8, String -> Date
   LocalDate localDate = LocalDate.parse(date, formatter);

// In Java 8, Date -> String
   formatter.format(localDate) // DateTimeFormatter

Refer to the table below for Date Time letter Patterns :

LetterDescriptionExamples
yYear2020
MMonth in yearJuly, 07, 7
dDay in month1-31
EDay name in weekFriday, Sunday
aAm/pm markerAM, PM
HHour in day0-23
hHour in am/pm1-12
mMinute in hour0-60
sSecond in minute0-60

Examples

1. String = “7-Jun-2020” to Date “dd-MMM-yyyy”

package com.test.dates;

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

public class DateUtility {

    public static void main(String[] args) {

        SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");

        String dateInString = "7-Jun-2020";

        try {
            Date date = formatter.parse(dateInString);
            System.out.println(date);
            System.out.println(formatter.format(date)); // returns a String

        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

OUTPUT

Sun Jun 07 00:00:00 IST 2020
07-Jun-2020

2. String = “07182020” to DateMMddyyyy

package com.test.dates;

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

public class DateUtility {

    public static void main(String[] args) {

        SimpleDateFormat formatter = new SimpleDateFormat("MMddyyyy");

        String dateInString = "07182020";

        try {
            Date date = formatter.parse(dateInString);
            System.out.println(date);
            System.out.println(formatter.format(date)); // returns a String

        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

OUTPUT

Sat Jul 18 00:00:00 IST 2020
07182020

3. In JAVA 8 using LocalDate API, Convert String “dd/MM/yyyy” to LocalDatedd/MM/yyyy

package com.test.dates;

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

public class DateJava8 {

    public static void main(String[] args) {

      DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/MM/yyyy");

      String date = "18/07/2020";

      LocalDate localDate = LocalDate.parse(date, formatter);

      System.out.println(localDate);

      System.out.println(formatter.format(localDate));
    }
}

OUTPUT

2020-07-18
18/07/2020

Summary

In this tutorial, we learnt how to convert String to Date in java using SimpleDateFormat and LocalDate of Java8.
Hope you liked it !


Leave a Comment