How to convert string to date in java in yyyy-mm-dd format?

Hi,

I have a date in yyyy-mm-dd format. How to convert string to date in java in yyyy-mm-dd format?

Thanks

View Answers

July 21, 2017 at 3:27 AM

Hi,

You can use the SimpleDateFormat class to format string to date.

Here is the full example code:

package net.roseindia;

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

/*
 * Example of formatting date in Java 
 * from yyyy-mm-dd formaat
 */
public class StringDateFormat {

    public static void main(String[] args) {

        String dt = "2017-05-08";
        String pattern = "yyyy-mm-dd";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        Date date = null;
        try {
            date = simpleDateFormat.parse(dt);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println("Date:" + date);

    }

}

Thanks


September 13, 2020 at 6:30 AM

Hi,

Small update: Use the MM in format, MM is for month. The small (mm) is for minute and you will get wrong results. Current format to be used is:

DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");

Thanks


September 13, 2020 at 6:33 AM

Hi,

Check all the date formatting options at:

Thanks


September 13, 2020 at 7:26 PM

Hi,

Here is the output of the program in Eclipse IDE:

Thanks









Related Tutorials/Questions & Answers:
Advertisements