在groovy/java中获取当前时间

在groovy/java中获取当前时间,java,groovy,Java,Groovy,我在groovy中有以下代码来获取以小时为单位的当前时间 def now = new Date() def time = now.getHours() 但是getHour()方法已被弃用。如果我在groovy/Java中使用此方法以及此方法的替代方法是什么?useCalendar Calendar cal=Calendar.getInstance();//it return same time as new Date() def hour = cal.get(Calendar.HO

我在groovy中有以下代码来获取以小时为单位的当前时间

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

但是getHour()方法已被弃用。如果我在groovy/Java中使用此方法以及此方法的替代方法是什么?

use
Calendar

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

有关详细信息,请阅读。

使用
日历

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

有关详细信息,请阅读。

您可以使用Joda time来获取当前时间或getHours

您可以使用Joda time来获取当前时间或getHours

尝试使用而不是标准的java.util.Date类。Joda时间库有更好的处理日期的API

DateTime dt = new DateTime();  // current time
int month = dt.getMonth();     // gets the current month
int hours = dt.getHourOfDay(); // gets hour of day
您可以使用像这样的传统类从给定的日期实例获取字段

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!
尝试使用而不是标准的java.util.Date类。Joda时间库有更好的处理日期的API

DateTime dt = new DateTime();  // current time
int month = dt.getMonth();     // gets the current month
int hours = dt.getHourOfDay(); // gets hour of day
您可以使用像这样的传统类从给定的日期实例获取字段

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!

它还告诉您如何使用可能重复的,实际上我想知道使用不推荐的方法的缺点。我唯一知道的是,jre的后一个版本将不包括它们,还有其他缺点吗?@sikander根据经验,我可以告诉你,
java.util.Date
中的那些方法已经被弃用了10多年了。我不会太担心它们被移除。我认为它们是不推荐使用的,因为整个Date类的设计忽略了所有时区的考虑因素。它还告诉您如何使用可能重复的方法,实际上我想知道使用不推荐使用的方法的缺点。我唯一知道的是,jre的后一个版本将不包括它们,还有其他缺点吗?@sikander根据经验,我可以告诉你,
java.util.Date
中的那些方法已经被弃用了10多年了。我不会太担心它们被移除。我认为它们不受欢迎,因为整个Date类的设计忽略了所有时区的考虑。