-1

I want to convert my String in format 2015-09-07 to Date in format 2015-09-07. While parsing the Date is getting in different format. I need the result Date in same format what the String is.

Thanks&Regards Sony K Koshy

  • 1
    use `SimpleDateFormat` – Blip Sep 07 '15 at 07:35
  • 3
    The short answer is, you can't. You can convert the `String` to a `Date` object, but `Date` has no concept of a format of it's own, it's just a container for the number of milliseconds from a fixed point in time. You can use a `SimpleDateFormat` to parse and format from/to a `String`, but otherwise you really shouldn't care – MadProgrammer Sep 07 '15 at 07:41

3 Answers3

1

Try like this":

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String str = "2015-09-07";
Date dt = sdf.parse(str);
System.out.println(dt);

Also refer: SimpleDateFormat for details.

Also you can create a generic function like this

private Date parseStringToDate(String dt, String format) throws ParseException
{
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    return sdf.parse(dt);
}
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0

Using SimpleDateFormat:

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    String dateString = "2015-09-07";
    Date date = simpleDateFormat .parse(dateString);
    System.out.println(date); //Mon Sep 07 00:00:00 CEST 2015
Fran Montero
  • 1,679
  • 12
  • 24
0
public class StringToDate {

    public static void main(String[] args) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("y-MM-dd");
        String stringDate = "2015-09-07";
        try {

            Date date = dateFormat.parse(stringDate);
            System.out.println(date); // it will display Mon Sep 07 00:00:00 IST 2015
            System.out.println(dateFormat.format(date));  // it will display 2015-09-07
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}
MJR
  • 31
  • 1
  • 9