在groovy/java中获取当前时间

sik*_*der 1 java groovy

我在groovy中有以下代码以获得当前时间.

def now = new Date()
  def time = now.getHours()
Run Code Online (Sandbox Code Playgroud)

但不推荐使用getHour()方法.如果我使用这个方法有什么缺点,在groovy/Java中这个方法的替代方法是什么?

Mas*_*dul 9

Calendar,

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

有关详细信息,请阅读此文档.


小智 9

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

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

您可以使用这样的传统类从给定的Date实例中获取字段.

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!
Run Code Online (Sandbox Code Playgroud)