日期:未检测到setTimeZone

时间:2019-07-26 15:52:43

标签: java android date datetime

我正在尝试将以毫秒为单位的日期转换为日期并获取时间。

我有以下代码:

 long yourmilliseconds = Long.parseLong(model_command.getTime());
    Date resultdate = new Date(yourmilliseconds);

当我调试并看到日期时,它给出的日期早了2小时。它只会在模拟器上产生此问题(可能不是在当地时间编程的)。我想解决此问题,以确保始终获得TimeZone GTM + 02中的时间,但我不知道该如何具体说。

我尝试过这样的事情:

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    long yourmilliseconds = System.currentTimeMillis();
    Date resultdate = new Date(yourmilliseconds);
    format.setTimeZone(TimeZone.getTimeZone("GTM+02"));
    String test = format.format(resultdate).toString(); /**DATE**/

但是以下行:format.setTimeZone(TimeZone.getTimeZone("GTM+02")); 似乎被忽略了,但仍然给出了错误的时间

有人可以帮忙吗?谢谢

2 个答案:

答案 0 :(得分:3)

SimpleDateFormat是一个传奇人物,使用Java 8中的ZonedDateTimeInstant

OffsetDateTime i = Instant.ofEpochMilli(yourmilliseconds)
        .atOffset(ZoneOffset.ofHours(2));

String dateTime = i.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));  //2019-07-26 18:01:49

但是,对于大多数用途而言,比指定偏移量更好的是以 region / city 格式指定时区,例如欧洲/布鲁塞尔:

ZonedDateTime i = Instant.ofEpochMilli(yourmilliseconds)
        .atZone(ZoneId.of("Europe/Brussels"));

在低于26的Android API级别上,您需要ThreeTenABP才能使用此现代解决方案。请参阅此question: How to use ThreeTenABP in Android Project以获取详细说明。

答案 1 :(得分:0)

GTM+02不是有效的ZoneId,我认为它应该是GMT+02