如何在 Java 中设置时间并且仅设置日历中的时间?

发布于 2024-07-12 07:22:51 字数 263 浏览 5 评论 0原文

有了小时和分钟,有没有比以下更简单或更好的方法将其设置到日历对象中:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

迎风吟唱 2024-07-19 07:22:51

此处

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

From here:

calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
旧梦荧光笔 2024-07-19 07:22:51

使用 set(int field ,整数值)。 第一个参数是小时/分钟/秒的字段编号。

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

滿滿的愛 2024-07-19 07:22:51

2018 年,没有人应该再使用 Calendar 类。 它早已过时,而现代 Java 日期和时间 API 的 java.time 使用起来要好得多。 相反,根据您的具体要求,使用 ZonedDateTimeOffsetDateTimeLocalDateTime。 无论哪种情况,请按以下方式设置一天中的时间:

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

链接 Oracle 教程日期时间

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:

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

Link: Oracle Tutorial Date Time

陌路终见情 2024-07-19 07:22:51

除了 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);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文