【问题标题】:converting from string to date object not displaying expected result [duplicate]从字符串转换为日期对象不显示预期结果[重复]
【发布时间】:2019-12-27 07:23:35
【问题描述】:

我搜索了解决方案但仍然无法正常工作,我正在尝试将日期对象的本地时区转换为 UTC +0,但是当我将日期对象格式化为 UTC 时,它正在工作。但是当我想再次将转换后的字符串转换为日期时,格式会发生变化,并且 UTC 在我将其存储在火存储之前会返回到 GMT+8。代码有什么问题?

这是我得到的当前日期对象

Calendar time = Calendar.getInstance();
time.setTimeZone(TimeZone.getTimeZone("UTC"));
Date current_time = time.getTime();

如果打印出来

Thu Aug 22 10:09:55 GMT+08:00 2019

然后我将其转换为 UTC

String dismissal_time_firestore;
Log.i(TAG, "Current time when swiped from phone time.getTime()  "+current_time);
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
dismissal_time_firestore = dateFormat.format(current_time);

知道了

Thu, 22 Aug 2019 02:09:55 +0000

但是当我将此字符串转换为日期对象时

try {
     current_time = dateFormat.parse(dismissal_time_firestore);
    } catch (ParseException e) {
      e.printStackTrace();
    }

我明白了

 Thu Aug 22 10:09:55 GMT+08:00 2019

【问题讨论】:

  • 你不能。老式的 Date 对象不能有时区或偏移量。请考虑通过 ThreeTenABP 使用现代 java.time。

标签: java datetime timezone utc


【解决方案1】:

您正在使用糟糕的日期时间类,这些类在几年前被 JSR 310 中定义的现代 java.time 类所取代。

您的主要问题是不了解Date::toString 方法对您来说是骗人的。它在生成文本时动态地将 JVM 的当前时区应用于 UTC 时刻。从不使用此类的众多原因之一。

以 UTC 获取当前时刻。

Instant instant = Instant.now() ;

以特定地区(时区)的人们使用的挂钟时间查看那个时刻。

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;

生成文本以显示给用户。

DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( Locale.CANADA_FRENCH ) ;
String output = zdt.format( f ) ;

您谈论解析格式化的字符串。馊主意。仅将日期时间值的文本表示视为输出,而不是输入。收集日期时间输入应该通过使用日期时间小部件来完成,而不是输入文本。

将日期时间值存储或交换为文本时,请始终使用ISO 8601 标准格式。 java.time 类在解析/生成字符串时默认使用 ISO 8601 格式。因此无需指定任何格式模式。只需致电parse/toString。示例:Instant.now().toString()Instant.parse( "2020-01-23T12:34:56.123456Z" )

我无法提供进一步的帮助,因为您并没有真正说出您想要完成的事情。

所有这些都在 Stack Overflow 上多次介绍过。因此,搜索以了解更多信息。并在发布前搜索。

【讨论】:

  • 感谢您的建议,我希望将格式化的字符串转换为日期对象,以便将其存储在 Firestore 中。我发现其他人建议将其存储为字符串,但我需要在应用程序的其他部分进行计算和查询。我可以知道你的建议吗?
  • @tasif99 将日期时间值存储或交换为文本时,始终使用ISO 8601 标准格式。 java.time 类在解析/生成字符串时默认使用 ISO 8601 格式。因此无需指定任何格式模式。只需致电parse/toString。示例:Instant.now().toString()
猜你喜欢
  • 2011-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-21
  • 2020-11-30
  • 2016-07-05
  • 1970-01-01
相关资源
最近更新 更多