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

Convert indian time zone to local time

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

下面是我的代码,但它似乎不起作用。

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"

更新: 检查使用现​​代 Java8 date-time api.

您不需要先更改 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("Asia/Kolkata"));
localSDF.setTimeZone(TimeZone.getDefault());

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

另一个答案使用 GMT+05:30,但最好使用适当的时区,例如 Asia/Kolkata.它现在有效,因为印度目前使用 +05:30 偏移量,但不能保证永远相同。

如果有一天政府决定改变国家的抵消(already happened in the past), your code with a hardcoded GMT+05:30 will stop working - but a code with Asia/Kolkata (and a )将继续工作。

但是今天有一个更好的API来操作日期,在这里查看如何配置它:

这比 SimpleDateFormat 好,class 已知有很多问题:https://eyalsch.wordpress.com/2009/05/29/sdf/

有了这个 API,代码将是:

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

在我的机器上,输出是2018-02-28 07:34:12(它根据您环境的默认时区而变化)。

虽然学习一个新的东西看起来很复杂API,但在这种情况下我认为这是完全值得的。新的 API 更好,更易于使用(一旦你了解了概念),更少 error-prone,并修复了旧 API.

的许多问题

查看 Oracle 的教程以了解更多信息:https://docs.oracle.com/javase/tutorial/datetime/