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

时间:2019-04-17 10:34:07

标签: android timezone simpledateformat timestamp-with-timezone

我的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));

格林尼治标准时间+7:timeString = 01:45(正确)

但是在GMT + 6.5时:timeString = 00:45(错误)->应该为01:15

您是否有建议按当地时间更正时间?

2 个答案:

答案 0 :(得分:0)

请尝试将其正常转换,例如

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

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

或者将其转换为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

希望这会有所帮助。

答案 1 :(得分: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"
    
相关问题