Java getHours(), getMinutes() and getSeconds()

mel picture mel · Nov 16, 2011 · Viewed 175k times · Source

As I know getHours(), getMinutes() and getSeconds() are all deprecated in Java and they are replaced with Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND.

These will in fact return the hour, minute and second for that particular moment. However, I would want to retrieved the hours and minutes from a Date variable. For instance,

say the time retrieved from database is

time = Thu Jan 01 09:12:18 CET 1970;

int hours = time.getHours();
int minutes = time.getMinutes();
int seconds = time.getSeconds();

By retrieving the hours, minutes, and seconds, I get

hours = 9
minutes = 12
seconds = 18

So, how do I use Calendar for this function? Although the getHours() has been deprecated but it still worked. I would still like to know if there is an alternative to this.

Answer

user998692 picture user998692 · Nov 16, 2011

Try this:

Calendar calendar = Calendar.getInstance();
calendar.setTime(yourdate);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);

Edit:

hours, minutes, seconds

above will be the hours, minutes and seconds after converting yourdate to System Timezone!