Java getHours(),getMinutes()和getSeconds()


81

据我所知getHours()getMinutes()getSeconds()在Java中都被弃用,它们与更换Calendar.HOUR_OF_DAYCalendar.MINUTECalendar.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

那么,如何将日历用于此功能?尽管getHours()已弃用,但仍然有效。我仍然想知道是否有替代方法。

Answers:


179

试试这个:

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
另外,如果需要设置时区,请添加TimeZone tz = TimeZone.getTimeZone(“ UTC”); // ...初始化日历calendar.setTimeZone(tz); <code>
Swaraj

33

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));

V有用的清单:可能是当今最常见的日期/时间系统集。
StephenBoesch

1
但是它以小时和分钟显示一位数。是否可以显示两位数
凤凰城

9

对于时差,请注意日历从1970年1月1日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


2
哇。在Java中如何进行日期操作几乎不可能的。
StephenBoesch
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.