英文:
Android Calendar does not show start of day, 00:00:00
问题
以下是您要翻译的代码部分:
我正在尝试创建一个日历对象,表示一天的开始,或者00:00:00
这是我的代码。
val calendarStart = Calendar.getInstance(TimeZone.getTimeZone("EST"), Locale.US)
calendarStart.time = Date()
calendarStart[Calendar.HOUR] = 0
calendarStart[Calendar.HOUR_OF_DAY] = 0
calendarStart[Calendar.MINUTE] = 0
calendarStart[Calendar.SECOND] = 0
calendarStart[Calendar.MILLISECOND] = 0
val utcStartDate = calendarStart.time
val calendarEnd = Calendar.getInstance(TimeZone.getTimeZone("EST"), Locale.US)
calendarEnd[Calendar.HOUR_OF_DAY] = 23
calendarEnd[Calendar.MINUTE] = 59
calendarEnd[Calendar.SECOND] = 59
calendarEnd[Calendar.MILLISECOND] = 999
val utcEndDate = calendarEnd.time
结束日期似乎没问题,但是开始日期显示为01:00:00,如调试日志的屏幕截图所示。
有人能解释一下为什么它显示为1:00:00,以及我如何创建一个一天的开始日历?
*** **更新** ***
#snachmsm给出的答案是正确的,并解决了问题。但是,我选择使用以下代码:
val dayStart: LocalDateTime = now.with(LocalTime.MIN)
val zdtStart: ZonedDateTime = dayStart.atZone(ZoneId.systemDefault())
val startDate = Date.from(zdtStart.toInstant())
val dayEnd: LocalDateTime = now.with(LocalTime.MAX)
val zdtEnd: ZonedDateTime = dayEnd.atZone(ZoneId.systemDefault())
val endDate = Date.from(zdtEnd.toInstant())
请注意,代码中的特殊字符“"”已被还原为正常的双引号。
英文:
I am trying to create a Calendar object for the start of the day, or 00:00:00
Here is my code.
val calendarStart = Calendar.getInstance(TimeZone.getTimeZone("EST"), Locale.US)
calendarStart.time = Date()
calendarStart[Calendar.HOUR] = 0
calendarStart[Calendar.HOUR_OF_DAY] = 0
calendarStart[Calendar.MINUTE] = 0
calendarStart[Calendar.SECOND] = 0
calendarStart[Calendar.MILLISECOND] = 0
val utcStartDate = calendarStart.time
val calendarEnd = Calendar.getInstance(TimeZone.getTimeZone("EST"), Locale.US)
calendarEnd[Calendar.HOUR_OF_DAY] = 23
calendarEnd[Calendar.MINUTE] = 59
calendarEnd[Calendar.SECOND] = 59
calendarEnd[Calendar.MILLISECOND] = 999
val utcEndDate = calendarEnd.time
The end date seems ok, but the start date shows as 01:00:00 as seen in the screenshot of the debugger log.
Can someone explain to me why it show as 1:00:00 and how do I create a start of day calendar?
*** UPDATE ***
The answer #snachmsm gave was correct and did solve the issue. However, I opted to use this code instead:
val dayStart: LocalDateTime = now.with(LocalTime.MIN)
val zdtStart: ZonedDateTime = dayStart.atZone(ZoneId.systemDefault())
val startDate = Date.from(zdtStart.toInstant())
val dayEnd: LocalDateTime = now.with(LocalTime.MAX)
val zdtEnd: ZonedDateTime = dayEnd.atZone(ZoneId.systemDefault())
val endDate = Date.from(zdtEnd.toInstant())
答案1
得分: 1
请注意,您正在尝试获取“EST”时区,但日志显示“EDT”时区 - 与您的情况一样,差异为1小时。
根据此链接,Android中的“EST”不使用夏令时。尝试使用getTimeZone("America/New_York")
。
英文:
note that you are trying to get EST
timezone and log shows EDT
timezone - 1h of difference like in your case
according to THIS EST
in Android doesn't use daylight saving. try to use getTimeZone("America/New_York")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论