【问题标题】:Scala TimeZone IssueScala 时区问题
【发布时间】:2015-10-08 16:25:15
【问题描述】:

我正面临这个问题,我将时区设置为 UTC,但它仍然显示 IST。

>>> import java.util.Calendar
>>> import java.util.TimeZone
>>> val cal = Calendar.getInstance()
>>> cal.setTimeZone(TimeZone.getTimeZone("UTC"))
>>> cal.getTimeZone().getDisplayName()
res95: String = Coordinated Universal Time  # here i got UTC
>>> cal.getTime()
res97: java.util.Date = Thu Oct 08 13:13:17 IST 2015
                                            ^^^   
                                    why here IST insted of UTC???

【问题讨论】:

标签: java scala timezone


【解决方案1】:

“getTime”函数返回一个 java Date 对象,它不知道您对 Calendar 对象进行的setTimeZone 调用。 Date 对象没有时区的概念,它只是自纪元以来毫秒的包装。您看到的输出只是 Scala REPL 用来描述对象的默认 toString 表示。您可以使用如下代码在特定时区将 Date 对象显式转换为 String:

import java.text.SimpleDateFormat
import java.util.{TimeZone, Date}

val formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
val date= new Date(1444291567242l); //java.util.Date = Thu Oct 08 09:06:07 BST 2015
val dateString = formatter.format(date); //String = 2015-10-08 08:06:07 UTC

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-16
    • 2016-09-12
    • 2020-07-11
    • 2012-02-27
    • 2011-06-15
    • 2021-01-26
    • 2020-02-17
    相关资源
    最近更新 更多