Java 日期和时间

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

Java Date & Time of Day

javadate

提问by Gaz

I have an application that passes in java.util.Date. I want to check whether this date is within a specified time of day (e.g. between 10:30 & 11:30), I don't care about the date, just the time of day.

我有一个传入 java.util.Date 的应用程序。我想检查这个日期是否在一天中的指定时间(例如 10:30 和 11:30 之间),我不关心日期,只关心一天中的时间。

Can anyone show me a simple way to do this?

谁能告诉我一个简单的方法来做到这一点?

Thanks

谢谢

回答by cletus

This is what the Calendarclass is for. Assuming dateis your Dateobject:

这就是Calendar班级的用途。假设date是你的Date对象:

Calendar cal = Calendar.getInstance();
cal.setTime(date);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minutes = cal.get(Calendar.MINUTE);
if (hour == 10 && minutes >= 30 || hour == 11 && minutes <= 30) {
   ... 
}