Sikander
Sikander

Reputation: 862

getting current time in groovy/java

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 ?

Upvotes: 1

Views: 31679

Answers (3)

Ramesh
Ramesh

Reputation: 416

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!

Upvotes: 9

Muhamamd Omar Muneer
Muhamamd Omar Muneer

Reputation: 885

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

Upvotes: -4

Masudul
Masudul

Reputation: 21971

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.

Upvotes: 9

Related Questions