据我所知getHours()
,getMinutes()
和getSeconds()
在Java中全部弃用,并被Calendar.HOUR_OF_DAY
,Calendar.MINUTE
,Calendar.SECOND
取代
实际上,这些将在特定时刻返回小时,分钟和秒。但是,我想从Date变量中检索小时和分钟。例如,
说从数据库检索的时间是
time = Thu Jan 01 09:12:18 CET 1970;
int hours = time.getHours();
int minutes = time.getMinutes();
int seconds = time.getSeconds();
通过检索小时,分钟和秒,我得到了
hours = 9
minutes = 12
seconds = 18
那么,我如何使用Calendar来实现这个功能呢?虽然getHours()
已被弃用但仍然有效。我仍然想知道是否有替代方案。
答案 0 :(得分:169)
试试这个:
Calendar calendar = Calendar.getInstance();
calendar.setTime(yourdate);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);
编辑:
hours, minutes, seconds
上面的是将yourdate
转换为系统时区后的小时,分钟和秒数!
答案 1 :(得分:31)
Java 8
System.out.println(LocalDateTime.now().getHour()); // 7
System.out.println(LocalDateTime.now().getMinute()); // 45
System.out.println(LocalDateTime.now().getSecond()); // 32
日历
System.out.println(Calendar.getInstance().get(Calendar.HOUR_OF_DAY)); // 7
System.out.println(Calendar.getInstance().get(Calendar.MINUTE)); // 45
System.out.println(Calendar.getInstance().get(Calendar.SECOND)); // 32
System.out.println(new DateTime().getHourOfDay()); // 7
System.out.println(new DateTime().getMinuteOfHour()); // 45
System.out.println(new DateTime().getSecondOfMinute()); // 32
Java 8
// 07:48:55.056
System.out.println(ZonedDateTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME));
// 7:48:55
System.out.println(LocalTime.now().getHour() + ":" + LocalTime.now().getMinute() + ":" + LocalTime.now().getSecond());
// 07:48:55
System.out.println(new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()));
// 074855
System.out.println(new SimpleDateFormat("HHmmss").format(Calendar.getInstance().getTime()));
// 07:48:55
System.out.println(new Date().toString().substring(11, 20));
答案 2 :(得分:9)
对于时差,请注意日历从01.01.1970,01:00开始,而不是在00:00开始。如果您正在使用java.util.Date和java.text.SimpleDateFormat,则必须补偿1小时:
long start = System.currentTimeMillis();
long end = start + (1*3600 + 23*60 + 45) * 1000 + 678; // 1 h 23 min 45.678 s
Date timeDiff = new Date(end - start - 3600000); // compensate for 1h in millis
SimpleDateFormat timeFormat = new SimpleDateFormat("H:mm:ss.SSS");
System.out.println("Duration: " + timeFormat.format(timeDiff));
这将打印:
持续时间:1:23:45.678