Reputation: 21
When I'm going to get a long with new Date().getTime()
, I find that when time > 11:59:59, it always resolve 00:xx:xx, for example; 12:00:00 --> 00:00:00, 12:23:56 --> 00:23:56;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date parse = null;
try {
parse = format.parse(str);
log.debug("time{}", parse);
} catch (ParseException e) {
e.printStackTrace();
}
when str = "2022-01-12 11:59:59"
it works well;
when str = "2022-01-12 12:00:00"
it works badly, it gives me 00:00:00;
when str = "2022-01-12 12:15:00"
it works badly,it give me 00:15:00;
when str = "2022-01-12 13:15:00"
it works well,it give me 13:00:00;
Upvotes: 2
Views: 1525
Reputation: 339482
LocalDateTime.parse( "2022-01-12 12:15:00".replace( " " , "T" ) )
As others said, your formatting pattern is incorrect in its use of hh
for 12-hour clock rather than HH
for 24-hour clock.
Furthermore, you are using terrible legacy date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310.
Your input strings nearly comply with the ISO 8601 standard for date-time strings. Replace the SPACE in the middle with a T
.
String input = "2022-01-12 12:15:00".replace( " " , "T" ) ;
Parse as a LocalDateTime
. No need to specify a formatting pattern.
LocalDateTime ldt = LocalDateTime.parse( input ) ;
Upvotes: 0
Reputation: 556
If you check the doc for SimpleDateFormat,
h == Hour in am/pm (1-12)
So 12pm is midnight.
If you want a 24hrs time, upper case 'H' rather than lower case 'h' to represent hour
H == Hour in day (0-23)
Upvotes: 3