Reputation: 992
My date in string format is 2016-09-17 12:12:44. I am converting it to date object by this:
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.ENGLISH);
Date endDate = sdf1.parse(expiry);
The output is Sat Sep 17 00:12:44 GMT+05:30 2016. However the output should be: Sat Sep 17 12:12:44 GMT+05:30 2016
Upvotes: 0
Views: 744
Reputation: 340148
LocalDateTime.parse( "2016-09-17 12:12:44".replace( " " , "T" ) )
The Answer by Crowder is correct.
Even easier is use with the modern java.time classes.
These classes use the standard ISO 8601 formats by default in parsing and generating strings. So no need to specify a formatting pattern for such strings.
Your input string can be made to comply by replacing SPACE in the middle with a T
.
String input = "2016-09-17 12:12:44".replace( " " , "T" );
We parse as a LocalDateTime
since your input lacks any info about offset-from-UTC nor time zone.
LocalDateTime ldt = LocalDateTime.parse( input );
By context, you know this value is meant to be a time in India. So apply a time zone of Asia/Kolkata
to get a ZonedDateTime
.
ZoneId z = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zdt = ldt.atZone( z );
Upvotes: 0
Reputation: 692
As mentioned in the document H - represents 24 hours format and h - represents 12 hours format with am/pm
So the format should be yyyy-MM-dd HH:mm:ss
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
Date endDate = sdf1.parse("2016-09-17 12:12:44");
System.out.println(endDate.toString());
Upvotes: 1
Reputation: 1075597
h
is "Hour in am/pm (1-12)". Without an am/pm indicator, the assumption is a.m. Use HH
where you have hh
:
String expiry = "2016-09-17 12:12:44";
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
// ------------------------------------------------------^^
Date endDate = sdf1.parse(expiry);
System.out.println(endDate);
Output:
Sat Sep 17 12:12:44 GMT 2016
...or update your string to include an am/pm indicator and add a
to the format string.
Upvotes: 1