M Sach M Sach - 5 months ago 15
Java Question

Issue i am facing with dateFormat.parse(string)?

I have below code snippet

SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd hh:mm:ss.SSS");
String processedContentDate="2012-04-10 12:53:28.033";
java.util.Date parsedDate = dateFormat.parse(processedContentDate);
java.sql.Timestamp timestamp = new java.sql.Timestamp(
parsedDate.getTime());


I get parsed date as Tue Apr 10 00:53:28 IST 2012 and timestamp as 2012-04-10 00:53:28.033 . i want to get the time exactly as 12:53:28.033(as in my original string)
not 00:53:28.033.
Not getting why 12:53:28 is getting converted to 00:53:28. what should I do to get 12:53:28?

EDIT: After getting the response, I tried this small programme where current time is 14:34:38.899
but at both lines i.e at line 1 and line 2, I got below parsed date
2012-04-10 14:34:38.899
As per reply I should have got 02:34:38.899 at line 1 as date format is
yyyy-MM-dd hh:mm:ss.SSS")


java.util.Date date= new java.util.Date();
String strDate=date.toString();
java.util.Date parsedDate;
java.util.Date parsedDate2;
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd hh:mm:ss.SSS");// line 1
SimpleDateFormat dateFormat2 = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss.SSS");//line 2
try {
java.sql.Timestamp timestamp = new java.sql.Timestamp(date.getTime());
strDate=timestamp.toString();


parsedDate = dateFormat.parse(strDate);//line1
parsedDate2 = dateFormat2.parse(strDate);//line2

Answer

Define your dateFormat like that

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

HH instead of hh. See SimpleDateFormat