在java中获取当前时区的日期 [英] Get date in current timezone in java

查看:1093
本文介绍了在java中获取当前时区的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在搜索从过去几个小时的网络,以获得datetime在我的系统时区。

I have been searching over the net from past few hours to get the datetime in my system timezone.

当我使用calendar.getTimezone.getDefaultName它总是返回我格林威治标准时间。 (理想情况下,它应该返回我当前的时区,这是IST)
我试图转换这个字符串2014-02-14T06:04:00:00,这是在GMT的我的时区datetime。
它总是返回我在GMT的同一时间。

When I use calendar.getTimezone.getDefaultName it always returns me GMT. (ideally it should return my current timezone, which is IST) I am trying to convert this string "2014-02-14T06:04:00:00", which is in GMT to my timezone datetime. It always returns me the same time in GMT.

我所看到的是每个人都建议使用时区。即

All I see is that everyone is suggesting to use Timezone. i.e,

dateFormatter.setTimezone("any_arbitary_timezone");

点是我的应用程序将在不同的地理位置使用。我无法将其设置为特定的时区。

Point is my application will be used in different geographical locations. I cannot set it to a particular timezone. It should be set to the system timezone, so that it can display in whichever timezone the user is currently in

推荐答案

这里是一个可以显示用户当前所在时区的系统时区以获取与您的本地系统时钟偏移量匹配的 TimeZone 的I​​D

Here is a way to get the id of a TimeZone that matches your local system clock's offset,

Calendar cal = Calendar.getInstance();
long milliDiff = cal.get(Calendar.ZONE_OFFSET);
// Got local offset, now loop through available timezone id(s).
String [] ids = TimeZone.getAvailableIDs();
String name = null;
for (String id : ids) {
  TimeZone tz = TimeZone.getTimeZone(id);
  if (tz.getRawOffset() == milliDiff) {
    // Found a match.
    name = id;
    break;
  }
}
System.out.println(name);

这篇关于在java中获取当前时区的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆