Java: getMinutes and getHours

2022-08-31 07:18:12

从那以后,您如何获得小时和分钟并被弃用?我在Google搜索上找到的示例使用了已弃用的方法。Date.getHoursDate.getMinutes


答案 1

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

请参阅此问题,了解使用Joda时间库的优缺点。

Joda Time 也可能作为标准组件包含在 Java 的某些未来版本中,请参阅 JSR-310


如果必须使用传统的 java.util.Date 和 java.util.Calendar 类,请参阅其 JavaDoc 以获取帮助(java.util.Calendarjava.util.Date)。

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

答案 2

来自 Javadoc for Date.getHours

As of JDK version 1.1, replaced by Calendar.get(Calendar.HOUR_OF_DAY)

所以使用

Calendar rightNow = Calendar.getInstance();
int hour = rightNow.get(Calendar.HOUR_OF_DAY);

和 getMinutes 的等效项。