[英]Java 8 Date API - Week of year is different for the same day but different time
For what I can only assume is a timezone issue, the following code yields different week of year values for the same day, but different times: 对于我只能假设是时区问题,以下代码会在同一天生成不同的一年中的值,但是时间不同:
Note, the code is written in Kotlin 注意,代码是用Kotlin编写的
Example 例
fun main(args: Array<String>) {
val middaySundayAfterEpoch = Instant.EPOCH + Duration
.ZERO
.plusDays(3)
.plusHours(12)
val almostMidnightSundayAfterEpoch = Instant.EPOCH + Duration
.ZERO
.plusDays(3)
.plusHours(23)
println(getWeekOfYear(middaySundayAfterEpoch))
println(getWeekOfYear(almostMidnightSundayAfterEpoch))
}
fun getWeekOfYear(instant: Instant): Int {
val calendar: Calendar = Calendar.getInstance()
calendar.time = Date.from(instant)
return calendar.get(Calendar.WEEK_OF_YEAR)
}
Results 结果
1
1
2
2
Assumptions 假设
Question 题
How do I modify this to ignore the time zone, so that both times occur in the same week? 如何修改此选项以忽略时区,以便两个时间都在同一周内发生?
You should never use the legacy java.util.Date
and java.util.Calendar
if you can possibly avoid them, this being one of many reasons. 如果可以避免使用遗留的
java.util.Date
和java.util.Calendar
则永远不要使用它们,这是众多原因之一。
The ZonedDateTime
object provides a way to get this: ZonedDateTime
对象提供了一种获取此方法的方法:
instant.atZone(ZoneId.of("UTC")).get(IsoFields.WEEK_OF_WEEK_BASED_YEAR)
EDIT: A previous version of this answer used the system default time, as well as ChronoUnit.ALIGNED_WEEK_OF_YEAR
. 编辑:此答案的先前版本使用系统默认时间,以及
ChronoUnit.ALIGNED_WEEK_OF_YEAR
。 This considers 1-7 January to be "week 1" of the year, regardless of on which day of the week 1 January lies in a particular year. 这将1月1日至7日视为一年中的“第1周”,无论1月1日哪一天是特定年份。 However, it will be based on the date part of the
ZonedDateTime
. 但是,它将基于
ZonedDateTime
的日期部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.