0

how can i make Date data type from String in java? input: String "2014/01/01 18:02:02" => output: Date 2014/01/01 18:02:02

hamed
  • 7,939
  • 15
  • 60
  • 114

6 Answers6

1

please use SimpleDateFormat to parse String To Date.

In there you can find suitable DateFormat to convert this String to Date.

Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
1

you can try this

String dateString = "2014/01/01 18:02:02";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime StringAsDate = LocalDateTime.parse(dateString, formatter);

I would recommend using Time(java.time) API instead of java.util for your Date & Time needs as it is new and exclusively added to java for Date & Time operations.

Abhay
  • 139
  • 2
  • 16
1

You could use a DateFormat to parse and format (they're reciprocal functions) the String. Something like,

String str = "2014/01/01 18:02:02";
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
try {
    Date d = df.parse(str);
    System.out.println(df.format(d));
} catch (ParseException e) {
    e.printStackTrace();
}

Output is (as requested)

2014/01/01 18:02:02
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

You can use the following code snippet -

String dateString = "10-11-2014";
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date inputDate = dateFormat.parse(dateString);
Razib
  • 10,965
  • 11
  • 53
  • 80
0

You can try this too.

SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String dateInString = "2014/01/01 18:02:02";
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));

It is a working and it is also suitable to you as it is not complicated. you will get this output:

Wed Jan 01 18:02:02 IST 2014
2014/01/01 18:02:02
Manoj Sharma
  • 596
  • 1
  • 6
  • 23
0

For your date following code should work :-

String myString = "2014/01/01 18:02:02";
DateFormat myDateFormat = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
Date myDate = myDateFormat.parse(myString);

For more details, see the documentation for SimpleDateFormat. Just make sure you use capital "MM" for month and small "mm" for minute.

Panther
  • 3,312
  • 9
  • 27
  • 50