问题
你怎么得到5886621865和Date.getMinutes
被弃用的小时和分钟?我在Google搜索中找到的示例使用了弃用的方法。
#1 热门回答(150 赞)
尝试使用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 Time库的优缺点,请参阅thisquestion。
Joda Time也可能作为标准组件包含在Java的某个未来版本中,参见JSR-310。
如果必须使用传统的java.util.Date和java.util.Calendar类,请参阅JavaDoc的帮助(java.util.Calendar和java.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 热门回答(77 赞)
来自Javadoc for Date.getHoursAs 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的等价物。
#3 热门回答(33 赞)
首先,导入java.util.Calendar
Calendar now = Calendar.getInstance();
System.out.println(now.get(Calendar.HOUR_OF_DAY) + ":" + now.get(Calendar.MINUTE));