1

I have the following code in groovy to get current time in hours.

def now = new Date()
  def time = now.getHours()

but the getHour() method is deprecated. What are the disadvantages if I use this method and the what is the alternative to this method in groovy/Java ?

Sikander
  • 834
  • 2
  • 10
  • 33
  • 1
    It tells you what to use [in the documentation](http://docs.oracle.com/javase/7/docs/api/java/util/Date.html#getHours%28%29) – tim_yates Dec 10 '13 at 06:50
  • 1
    possible duplicate of [Java: getMinutes and getHours](http://stackoverflow.com/questions/907170/java-getminutes-and-gethours) – tim_yates Dec 10 '13 at 06:52
  • Also http://stackoverflow.com/questions/8150155/java-gethours-getminutes-and-getseconds and http://stackoverflow.com/questions/13343524/the-correct-way-to-set-and-get-hour-minutes-sec – tim_yates Dec 10 '13 at 06:55
  • actually I want to know the disadvantages of using deprecated methods. the only one I know is that latter version of jre will not include them, are there any other disadvantages ? – Sikander Dec 10 '13 at 06:58
  • It was deprecated for a reason. Usually thread safety, poor design, or just not working correctly. http://stackoverflow.com/questions/2901262/why-were-most-java-util-date-methods-deprecated – tim_yates Dec 10 '13 at 07:02
  • 2
    @sikander I can tell you from experience that those methods in `java.util.Date` have been deprecated for over 10 years now. I wouldn't be too concerned about them actually being removed. I think they are deprecated because the entire Date class' design ignores all timezone considerations. – dsh Aug 26 '16 at 15:44

3 Answers3

9

Use Calendar,

  Calendar cal=Calendar.getInstance();//it return same time as new Date()
  def hour = cal.get(Calendar.HOUR_OF_DAY)

For details, read this docs.

Masudul
  • 21,823
  • 5
  • 43
  • 58
9

Try using Joda Time instead of standard java.util.Date classes. Joda Time library has much better API for handling dates.

DateTime dt = new DateTime();  // current time
int month = dt.getMonth();     // gets the current month
int hours = dt.getHourOfDay(); // gets hour of day

You can use the traditional classes like this to fetch fields from given Date instance.

Date date = new Date();   // given date
Calendar calendar = GregorianCalendar.getInstance(); // creates a new calendar instance
calendar.setTime(date);   // assigns calendar to given date 
calendar.get(Calendar.HOUR_OF_DAY); // gets hour in 24h format
calendar.get(Calendar.HOUR);        // gets hour in 12h format
calendar.get(Calendar.MONTH);       // gets month number, NOTE this is zero based!
Rob Kielty
  • 7,958
  • 8
  • 39
  • 51
Ramesh
  • 416
  • 3
  • 10
-3

You can use Joda-time for get current time or getHours