你如何在 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
How do you set the time and only the time in a calendar in Java?
提问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
回答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 Calendar
class anymore. It it long outmoded, and java.time
the modern Java date and time API is so much nicer to work with. Instead use, depending on you exact requirements, a ZonedDateTime
or perhaps an OffsetDateTime
or LocalDateTime
. In either case, set the time of day this way:
在 2018 年,没有人应该再使用这个Calendar
类了。它早已过时了,而java.time
现代 Java 日期和时间 API 使用起来要好得多。取而代之的是,根据您的确切要求,使用 aZonedDateTime
或者可能是OffsetDateTime
或LocalDateTime
。在任何一种情况下,都可以这样设置一天中的时间:
dateTime = dateTime.with(LocalTime.of(hour, minute));