在java中询问公历一天中的小时
我使用公历来使用公历的 set 函数为应用程序设置特定的日期和时间。当我使用 getTime() 方法时,它给出了正确的输出,但是当我尝试访问 Hour_Of_Day 和 Minute 时,它给出了错误的数字。
Calendar time = new GregorianCalendar();
time.set(2010, Calendar.JANUARY, 1, 7, 20,0);
hour = time.HOUR_OF_DAY;
minute = time.MINUTE;
小时给出的输出为 11,分钟给出的值为 12。
关于如何解决这个问题有什么建议吗? 谢谢
I'm using a Gregorian Calendar to set a specific date and time to an application using the set function of the Gregorian Calendar. When i use the getTime() method, it gives me the right output however when i try to access the Hour_Of_Day and Minute it gives a wrong number.
Calendar time = new GregorianCalendar();
time.set(2010, Calendar.JANUARY, 1, 7, 20,0);
hour = time.HOUR_OF_DAY;
minute = time.MINUTE;
The hour gives an output of 11 and the minute gives an a value of 12.
Any suggestions on how to fix this?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的代码只是将小时/分钟分配给常量。您需要调用 Calendar.get(int):
Your code is just assigning hour/minute to constants. You need to call Calendar.get(int):
tl;dr
java.time
使用现代 java.time 类替换那些麻烦的旧遗留日期时间类会更容易。
ZonedDateTime
class 表示特定时区时间线上的时刻,分辨率为纳秒。使用添加到旧类中的新方法从
GregorianCalendar
进行转换。或者在没有 GregorianCalendar 类的情况下重新开始。
如果您只想使用一天中的时间部分,请提取
LocalTime
。如果您确实想要整数小时和分钟,您可以询问这些。
关于 java.time
java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧遗留日期时间类,例如
java.util.Date
,日历
, & ;SimpleDateFormat
。Joda-Time 项目,现已在 维护模式,建议迁移到 java.time 类。
要了解更多信息,请参阅 Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范为 JSR 310。
从哪里获取 java.time 类?
ThreeTen-Extra 项目通过附加类扩展了 java.time 。该项目是 java.time 未来可能添加的内容的试验场。您可能会在这里找到一些有用的类,例如
间隔
,YearWeek
,<代码>YearQuarter,以及更多 。tl;dr
java.time
Much easier with the modern java.time classes that replace those troublesome old legacy date-time classes.
The
ZonedDateTime
class represents a moment on the timeline in a specific time zone with a resolution of nanoseconds.Convert from your
GregorianCalendar
using new methods added to the old classes.Or start fresh without the
GregorianCalendar
class.If you want to work with just the time-of-day portion, extract a
LocalTime
.If you really want the integer numbers of hours and minutes, you can interrogate for those.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as
java.util.Date
,Calendar
, &SimpleDateFormat
.The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as
Interval
,YearWeek
,YearQuarter
, and more.