你如何在 Java 中设置日历中的时间和时间?

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

How do you set the time and only the time in a calendar in Java?

javadatecalendarhourminute

提问by pupeno

Having the hours and minutes, is there any easier or better way to set it into a Calendar object than:

拥有小时和分钟,是否有比以下更简单或更好的方法将其设置为 Calendar 对象:

calendar.set(calendar.get(Calendar.YEAR),
                        calendar.get(Calendar.MONTH),
                        calendar.get(Calendar.DAY_OF_MONTH),
                        hour, minute);

采纳答案by Xn0vv3r

From here:

这里

calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);

回答by Rahul

Use set(int field, int value). The first parameter is the field number for HOUR/MINUTE/SECOND.

使用set(int field, int value)。第一个参数是 HOUR/MINUTE/SECOND 的字段编号。

回答by Ole V.V.

In 2018 no one should use the Calendarclass anymore. It it long outmoded, and java.timethe modern Java date and time API is so much nicer to work with. Instead use, depending on you exact requirements, a ZonedDateTimeor perhaps an OffsetDateTimeor LocalDateTime. In either case, set the time of day this way:

在 2018 年,没有人应该再使用这个Calendar类了。它早已过时了,而java.time现代 Java 日期和时间 API 使用起来要好得多。取而代之的是,根据您的确切要求,使用 aZonedDateTime或者可能是OffsetDateTimeLocalDateTime。在任何一种情况下,都可以这样设置一天中的时间:

dateTime = dateTime.with(LocalTime.of(hour, minute));

Link: Oracle Tutorial Date Time

链接Oracle 教程日期时间