Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String to java.util.Date

I am storing the dates in a SQLite database in this format:

d-MMM-yyyy,HH:mm:ss aaa 

When I retrieve the date with that format I am get every thing fine except the hour. The hour is always 00. Here is my output:

String date--->29-Apr-2010,13:00:14 PM After convrting Date--->1272479414000--Thu Apr 29 00:00:14 GMT+05:30 2010 

Here is the code:

    Date lScheduledDate = CalendarObj.getTime();     DateFormat formatter = new SimpleDateFormat("d-MMM-yyyy,HH:mm:ss aaa");     SomeClassObj.setTime(formatter.format(lScheduledDate));      String lNextDate = SomeClassObj.getTime();     DateFormat lFormatter = new SimpleDateFormat("d-MMM-yyyy,HH:mm:ss aaa");     Date lNextDate = (Date)lFormatter.parse(lNextDate);     System.out.println("output here"+lNextDate); 

What am I doing wrong?

like image 631
Vinayak Bevinakatti Avatar asked Apr 29 '10 05:04

Vinayak Bevinakatti


People also ask

Can we convert string to date in java?

We can convert String to Date in java using parse() method of DateFormat and SimpleDateFormat classes.

How do you convert a string to a date?

SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy", Locale. ENGLISH); String dateInString = "7-Jun-2013"; Date date = formatter. parse(dateInString); In the above example, we first need to construct a SimpleDateFormat object by passing the pattern describing the date and time format.

How do I get java Util date?

For the legacy java. util. Date , uses new Date() or new Date(System. currentTimeMillis() to get the current date time, and format it with the SimpleDateFormat .

What is java Util date format?

Date format conversion yyyy-mm-dd to mm-dd-yyyy.


1 Answers

I think your date format does not make sense. There is no 13:00 PM. Remove the "aaa" at the end of your format or turn the HH into hh.

Nevertheless, this works fine for me:

String testDate = "29-Apr-2010,13:00:14 PM"; DateFormat formatter = new SimpleDateFormat("d-MMM-yyyy,HH:mm:ss aaa"); Date date = formatter.parse(testDate); System.out.println(date); 

It prints "Thu Apr 29 13:00:14 CEST 2010".

like image 198
Thomas Lötzer Avatar answered Sep 18 '22 12:09

Thomas Lötzer