如何在 Java 中设置时间并且仅设置日历中的时间?
有了小时和分钟,有没有比以下更简单或更好的方法将其设置到日历对象中:
calendar.set(calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH),
hour, minute);
Having the hours and minutes, is there any easier or better way to set it into a Calendar object than:
calendar.set(calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH),
hour, minute);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
从此处:
From here:
使用 set(int field ,整数值)。 第一个参数是小时/分钟/秒的字段编号。
Use set(int field, int value). The first parameter is the field number for HOUR/MINUTE/SECOND.
2018 年,没有人应该再使用
Calendar
类。 它早已过时,而现代 Java 日期和时间 API 的java.time
使用起来要好得多。 相反,根据您的具体要求,使用ZonedDateTime
或OffsetDateTime
或LocalDateTime
。 无论哪种情况,请按以下方式设置一天中的时间:链接: Oracle 教程日期时间
In 2018 no one should use the
Calendar
class anymore. It it long outmoded, andjava.time
the modern Java date and time API is so much nicer to work with. Instead use, depending on you exact requirements, aZonedDateTime
or perhaps anOffsetDateTime
orLocalDateTime
. In either case, set the time of day this way:Link: Oracle Tutorial Date Time
除了 Xn0vv3r 接受的答案之外,不要忘记设置
calendar.set(Calendar.SECOND , 0);
In addition to the great accepted answer by Xn0vv3r, don't forget to set
calendar.set(Calendar.SECOND, 0);