Java 从日期获取小时、分钟和秒?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25474033/
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-11 00:28:12  来源:igfitidea点击:

Getting hours,minutes, and seconds from Date?

javaswingdatetime

提问by Carlton

I want to get the current hour,minute, and second from the Dateobject.

我想从Date对象中获取当前的小时、分钟和秒。

This is my code:

这是我的代码:

Date date = new Date();
int hour = date.getHours();

But I get a kind of error, the getHours()part doesnt work. I get a "The method getHours() from the type Data is deprecated". What does that mean, and how do I get the hour,minutes, and seconds?

但是我得到了一种错误,该getHours()部分不起作用。我得到一个“来自 Data 类型的方法 getHours() 已被弃用”。这是什么意思,我如何获得小时、分钟和秒?

采纳答案by nanofarad

Use Calendar:

使用Calendar

Calendar cal = Calendar.getInstance();
cal.setTime(date);  
int hours = cal.get(Calendar.HOUR_OF_DAY);

From Datejavadoc:

Datejavadoc

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

Returns the number of minutes past the hour represented by this date, as interpreted in the local time zone. The value returned is between 0 and 59.

已弃用。从 JDK 1.1 版开始,由Calendar.get(Calendar.MINUTE).

返回此日期表示的小时后的分钟数,如本地时区中所解释的那样。返回值介于 0 到 59 之间。