使用GMT + 6.5,SImpleDateFormat返回错误的值

问题描述 投票:0回答:2

我有一个长时间的UTC时间:1555415100000L

我使用此源代码按时区转换为本地时间。

//data.getTime() = 1555415100000L
String timeFormat = "HH:mm";
SimpleDateFormat sdf = new SimpleDateFormat(timeFormat);
long gmtTime = Long.parseLong(data.getTime()) + TimeZone.getDefault().getRawOffset();
String timeString = sdf.format(new Date(gmtTime));

在GMT + 7:timeString = 01:45(正确)

但是在GMT + 6.5:timeString = 00:45(不正确) - >应该是01:15

您有什么建议在当地纠正时间吗?

android timezone simpledateformat timestamp-with-timezone
2个回答
0
投票

一些东西:

  • 通过添加或减去偏移量来操作时间戳绝不是以任何语言转换时区的正确方法。始终寻找允许您使用time zone identifiers的API。如果你操纵时间戳,你就会刻意选择一个不同的时间点。这与调整本地时区的概念不同。
  • 世界上只有两个时区使用+6.5。他们是Asia/Yangon(在缅甸)和Indian/Cocos(在科科斯/基林群岛)。你应该使用其中一个。
  • 关于该时间戳的本地时间的断言是不正确的。 1555415100000对应于2019-04-16T11:45:00.000Z的UTC时间 +7偏移,即2019-04-16T18:45:00.000+07:00(18:45,而不是你说的01:45) 偏移+6.5,即2019-04-16T18:15:00.000+06:30(18:15,而不是01:15)
  • 你应该考虑使用Java 8引入的java.time package。在Android上,你可以使用ThreeTenABP library,这是Android的java.time API的后端。 import java.time.*; import java.time.format.*; ... long time = 1555415100000L; Instant instant = Instant.ofEpochMilli(time); ZonedDateTime zonedDateTime = instant.atZone(ZoneId.of("Asia/Yangon")); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm"); System.out.println(formatter.format(zonedDateTime)); //=> "18:15"
  • 如果你真的坚持使用较旧的日期和时间API,尽管他们记录了很多问题,那么你需要设置格式化程序的时区而不是操纵时间戳。 import java.util.*; import java.text.*; ... long time = 1555415100000L; long date = new Date(time)); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); sdf.setTimeZone(TimeZone.getTimeZone("Asia/Yangon")); System.out.println(sdf.format(date); //=> "18:15"

0
投票

请尝试正常转换,例如,

long time = 1555415100000L;
SimpleDateFormat sdf = new SimpleDateFormat();
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(sdf.format(new Date(time)));

我在在线java编译器中得到的输出:4/16/19 11:45 AM

或者如果将其转换为GMT,

long time = 1555415100000L;
Date date = new Date(time);
DateFormat gmt = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);
gmt.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(gmt.format(date));

在线编译器的输出:2019年4月16日格林尼治标准时间上午11:45:00

希望这可以帮助。

© www.soinside.com 2019 - 2024. All rights reserved.