0

I'm trying to get the current time using

Date date = new Date().getHours();

But I see it's been depracated in SE 7. Also I'm trying to create a Date object and then just setting the hours on it using

Date date = new Date().setHours();

And that's been deprecated as well. Let me lay out what I want to do: I want to run a process when it's between midnight and 5am in the morning. The way I'll do this (or wanted to do anyways), was create two variables. One indicating the start time (being midnight) and the other the stop time (5 am).

I would then loop the program the whole time every 5 mins, getting the current time and comparing it to the start time and stop time to see if it falls between those two times. And then start the processes that I want to run.

So with all this method deprication (Wish I knew the reasoning behind it), what's currently the best way to do that in SE 7?

PS - Since I'm only concerned with the time, is it even necessary to use the Date class and not something else?

3 Answers3

4

You can handle with this by using a calendar-instance.

Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR, 5); //hours to add
JavaDM
  • 851
  • 1
  • 6
  • 29
2

There are better alternatives like Calendar and TimerTasks, but if you want to manage with dates, you can use something like:

final long FIVE_HOURS = 5 * 60 * 60 * 1000;
Date startTime = new Date();
Date endTime = new Date(startTime.getTime() + FIVE_HOURS);
rocketboy
  • 9,573
  • 2
  • 34
  • 36
  • Thank you very much, I think I'll then rather use Calendar an TimerTask like you suggested. –  Sep 05 '13 at 09:34
1

Use Joda Time. It is a vastly superior Date and Time API, and my understanding is that it will become part of the core Java libraries under Java 8 (correct me if I am wrong here).

The core class is DateTime, and you can do things like this

int hours = new DateTime().getHoursOfDay();

and

new DateTime().setHoursOfDay(hours);

It is much faster and more efficient than Calendar.


Just noticed your PS - Joda also has a class called LocalTime which should be perfect if you only care about the time and not the date

Tom McIntyre
  • 3,620
  • 2
  • 23
  • 32
  • Very nice, simple and effective I'll rather go with this then, that Calendar class seems a bit heavy and messy. Would be great if it did become part of Java 8 –  Sep 05 '13 at 09:36