Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set time to 00:00:00 doesn't work - java

Tags:

java

I want to set string that contain the new current date and the time 00:00:00. I wrote the following code but time is set to 12:00:00

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
String today1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").
                  format(calendar.getTime())

I'd love to know why the code does not work or, alternatively, get another method to set time to 00:00:00

like image 806
Ido Ikar Avatar asked Jan 07 '23 15:01

Ido Ikar


1 Answers

You've used the format characters hh, which is the 12-hour, or am/pm, based hour scheme.

h Hour in am/pm (1-12) Number 12

You've printed 12:00 am without the "am". The time of day is set to midnight, but with your format "yyyy-MM-dd hh:mm:ss" the output is confusing at best.

You can do either of the following:

Switch to capital "H" characters to switch to a 24-hour clock as per your requirements:

H Hour in day (0-23) Number 0

new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")

Output:

2016-02-18 00:00:00

Or you can add the "a" format character to add the am/pm designation.

a Am/pm marker Text PM

new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a")

Output:

2016-02-18 12:00:00 AM
like image 136
rgettman Avatar answered Jan 15 '23 03:01

rgettman