java获取当前时区,在java中获取当前时区的日期

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

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

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Java的TimeZone类获取客户端时区信息。 在服务器端Java,可以通过获取HTTP请求头的"TimeZone"信息来获取客户端时区。具体实现如下: ```java import java.util.TimeZone; public class TimeZoneUtil { public static String getClientTimeZone(HttpServletRequest request) { String timeZone = request.getHeader("TimeZone"); if (timeZone == null || timeZone.isEmpty()) { return "UTC"; } return timeZone; } public static TimeZone getTimeZone(String timeZone) { if (timeZone == null || timeZone.isEmpty()) { return TimeZone.getTimeZone("UTC"); } return TimeZone.getTimeZone(timeZone); } } ``` 在上面的代码,getClientTimeZone方法会获取HTTP请求头的"TimeZone"信息,如果没有该信息则默认返回UTC时区。 getTimeZone方法根据传入的时区信息获取对应的TimeZone对象,如果传入的时区信息为空,则默认返回UTC时区。 使用示例: ```java import java.util.TimeZone; public class Main { public static void main(String[] args) { // 假设客户端时区为东八区 String clientTimeZone = "Asia/Shanghai"; // 获取对应的TimeZone对象 TimeZone timeZone = TimeZoneUtil.getTimeZone(clientTimeZone); System.out.println(timeZone.getID()); // 输出: Asia/Shanghai System.out.println(timeZone.getDisplayName()); // 输出: 国标准时间 System.out.println(timeZone.getRawOffset()); // 输出: 28800000 } } ``` 在上面的示例,我们传入客户端时区为"Asia/Shanghai",使用TimeZoneUtil类获取对应的TimeZone对象,并输出相关信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值