我正在尝试使用以下代码设置日历时间和分钟
Calendar c=Calendar.getInstance();
c.set(Calendar.HOUR,4);
c.set(Calendar.MINUTE, 23);
但它始终显示11小时和12小时。
答案 0 :(得分:0)
ZonedDateTime.of( // Represent a moment on the timeline adjusted into a particular time zone.
LocalDate.now( ZoneId.of( "Pacific/Auckland" ) ) , // Capture the current date for a particular time zone.
LocalTime.of( 4 , 23 ) , // Hard-code the time-of-day value desired. Will be adjusted as needed to handle anomalies such as DST.
ZoneId.of( "Pacific/Auckland" ) // Apply a particular time zone to this date-time.
)
你正在使用现在遗留下来的麻烦的旧日期时间类,取而代之的是 java.time 类。
您似乎希望当前日期具有特定的时间。
您忽略了时区的关键问题。时区对于确定日期至关重要。对于任何给定的时刻,日期在全球范围内因地区而异。例如,在Paris France午夜后的几分钟是新的一天,而Montréal Québec中仍然是“昨天”。
如果未指定时区,则JVM会隐式应用其当前的默认时区。该默认值可能随时更改,因此您的结果可能会有所不同。最好明确指定您期望/预期的时区作为参数。
以continent/region
的格式指定proper time zone name,例如America/Montreal
,Africa/Casablanca
或Pacific/Auckland
。切勿使用诸如EST
或IST
之类的3-4字母缩写,因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。
ZoneId z = ZoneId.of( "America/Montreal" ) ;
如果要使用JVM的当前默认时区,请求它并作为参数传递。如果省略,则隐式应用JVM的当前默认值。最好是明确的。
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
确定今天特定时区的当前日期。
LocalDate today = LocalDate.now( z ) ;
代表您的目标时间。
LocalTime lt = LocalTime.of( 4 , 23 ) ;
与区域合并以获得ZonedDateTime
。如果由于夏令时(DST)等异常而导致该时区的某个时间无效,则该课程会自动调整时间。
ZonedDateTime zdt = ZonedDateTime.of( today , lt , z ) ;
java.time框架内置于Java 8及更高版本中。这些类取代了麻烦的旧legacy日期时间类,例如java.util.Date
,Calendar
和& SimpleDateFormat
现在位于Joda-Time的maintenance mode项目建议迁移到java.time类。
要了解详情,请参阅Oracle Tutorial。并搜索Stack Overflow以获取许多示例和解释。规范是JSR 310。
从哪里获取java.time类?