在 groovy/java 中获取当前时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20487323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 02:15:53  来源:igfitidea点击:

getting current time in groovy/java

javagroovy

提问by sikander

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

我在 groovy 中有以下代码以获取当前时间(以小时为单位)。

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 ?

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

采纳答案by Masudul

Use Calendar,

使用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.

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

回答by Muhamamd Omar Muneer

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

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

回答by Ramesh

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

尝试使用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

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

您可以使用像这样的传统类从给定的 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!