What is an alternate method for setHours()
of java.util.Date
as it is deprecated. To my date variable, I want to set certain hours but I don't want to use the deprecated method setHours()
.
"The Calendar class should be used instead" - For Java 8 and later, the java. time. * classes are the better option ... if you are changing your code.
The setTime() method of Java Date class sets a date object. It sets date object to represent time milliseconds after January 1, 1970 00:00:00 GMT. Parameters: The function accepts a single parameter time which specifies the number of milliseconds. Return Value: It method has no return value.
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 .
Try this:
Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR_OF_DAY, hour); Date date = cal.getTime();
If you have a Date
object already, you can use cal.setTime(date)
to initialize calendar with the given date.
JavaDoc for Calendar.HOUR_OF_DAY
Field number for get and set indicating the hour of the day. HOUR_OF_DAY is used for the 24-hour clock. E.g., at 10:04:15.250 PM the HOUR_OF_DAY is 22.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With