Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternate method for setHours() of java.util.Date?

Tags:

java

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().

like image 464
Amruta Avatar asked Feb 16 '13 12:02

Amruta


People also ask

What can I use instead of a new date in Java?

"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.

How do you set a specific time in Java?

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.

How do I get Java Util date?

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 .


1 Answers

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.

like image 141
ogzd Avatar answered Sep 20 '22 14:09

ogzd