Saturday, 26 September 2015

How to Convert String to Date in Java in yyyy-MM-dd format

 In this tutorial, I will show you how to convert String to Date in Java which is in yyyy-mm-dd format. We will use DateFormat and SimpleDateFormat class from java.util.text package for this conversion.

Here are the steps :
1) Create a DateFormat with format String as "yyyy-MM-dd" (remember, small "m" is for minutes, and capital "M" is for month)
2) Call the parse() method with given String, this will return a java.util.Date object



Here is Example :

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

/**
 * How to convert String to date in yyyy-MM-dd format.
 *
 * @author WINDOWS 10
 *
 */
public class StringToDateParser{

    public static void main(String args[]) {

        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Scanner sc = new Scanner(System.in);

        System.out.println("Please enter a date in yyyy-MM-dd format e.g. 2015-02-23");

        String dateString = sc.next();

        // converting date to String
        try {
            Date date = formatter.parse(dateString);
            System.out.println("converted date : " + date);
        } catch (ParseException e) {
            System.out.printf("Sorry, given Date %s is invalid", dateString);
        }

        sc.close();

    }

}


Output :

Please enter a date in yyyy-MM-dd format e.g. 2015-02-23
2015-09-27
converted date : Sun Sep 27 00:00:00 GMT+08:00 2015

You can see that our program has successfully parse the given date String into a java.util.Date object. You can use these steps to convert any Date String e.g. dd-MM-yyyy or dd/MM/yyyy to a real Date object in Java.
Btw, just remember that SimpleDateformat is not thread-safe and should not be stored in static variable and should not be shared between multiple threads.

No comments:

Post a Comment