将印度时区转换为当地时间

问题描述 投票:-1回答:2

在我的应用程序中,我在IST时区的API服务器中获取时间,我想在设备的本地时区显示时间。

下面是我的代码,但它似乎无法正常工作。

SimpleDateFormat serverSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat utcSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat localSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
serverSDF.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
utcSDF.setTimeZone(TimeZone.getTimeZone("UTC"));
localSDF.setTimeZone(TimeZone.getDefault());

Date serverDate = serverSDF.parse(dateString);
String utcDate = utcSDF.format(serverDate);
Date localDate = localSDF.parse(utcDate);

从服务器我在IST得到时间"2018-02-28 16:04:12",上面的代码显示"Wed Feb 28 10:34:12 GMT+05:30 2018"

android timezone simpledateformat datetime-format gmt
2个回答
0
投票

您无需先以UTC格式更改格式。你可以简单地使用:

SimpleDateFormat serverSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat localSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
serverSDF.setTimeZone(TimeZone.getTimeZone("GMT+05:30"));
localSDF.setTimeZone(TimeZone.getDefault());

String localDate = localSDF.format(serverSDF.parse(dateString));

1
投票

另一个答案使用GMT + 05:30,但使用适当的时区如亚洲/加尔各答要好得多。它现在有效,因为印度目前使用+05:30偏移,但不能保证永远是相同的。

如果有一天政府决定改变国家的抵消额(already happened in the past),你的代码用硬编码的格林尼治标准时间+05:30将停止工作 - 但亚洲/加尔各答(以及JVM with the timezone data updated)的代码将继续有效。

但今天有一个更好的API来操纵日期,请参见此处如何配置它:How to use ThreeTenABP in Android Project

这比SimpleDateFormat更好,https://eyalsch.wordpress.com/2009/05/29/sdf/是一个众所周知的问题:String serverDate = "2018-02-28 16:04:12"; DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime istLocalDate = LocalDateTime.parse(serverDate, fmt); // set the date to India timezone String output = istLocalDate.atZone(ZoneId.of("Asia/Kolkata")) // convert to device's zone .withZoneSameInstant(ZoneId.systemDefault()) // format .format(fmt);

使用此API,代码将是:

2018-02-28 07:34:12

在我的机器中,输出是https://docs.oracle.com/javase/tutorial/datetime/(它根据您环境的默认时区而变化)。

虽然学习新API似乎很复杂,但在这种情况下,我认为这是完全值得的。新API更好,更易于使用(一旦您学习了概念),更不容易出错,并解决了旧API的许多问题。

查看Oracle的教程以了解更多信息:qazxswpoi

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