Java在运行时设置时区 [英] Java set timezone at runtime

查看:985
本文介绍了Java在运行时设置时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发桌面应用程序。它将从具有以下内容的用户输入文本文件:

I am working on a desktop application. It would get input as a text file from user having contents like this :

..................................   
..................................

Mon Jul  9 14:41:07 MDT 2012
..................................
..................................
..................................

我正在使用此信息并使用jfreechart库创建时间序列图表。时区可以是世界上任何可用的东西。但是当我使用这个文件时,它的默认时区是sytem的时区(IST),所以不显示MDT时间。当我尝试从日期捕获时区然后使用

I am using this information and creating a timeseries chart using jfreechart library. Timezone could be anything available in the world. But when I use this file its default timezone is sytem's timezone(IST) so doesn't show MDT time. When I tried to capture timezone from date and then used

TimeZone.setDefault(TimeZone.getTimeZone("MDT"));

它不起作用。当我有缩写MDT,CDT等时区时,如何更改Java中的默认时区?

It didn't work. How can I change the default timezone in Java when I am having abbreviation for timezone like MDT, CDT etc?

推荐答案

谢谢大家。感谢您的快速回复。 @vikas你的回答证明更有用。我正在使用以下代码并且运行良好。

Thanks Guys. Thanks for quick responses. @vikas your response proves to be more useful. I am using following code and it worked well.

String timezoneLongName = "";

String fileTimeZone     = "MDT"; //timezone could be anything, getting from file.

Date date            = new Date();
String TimeZoneIds[] = TimeZone.getAvailableIDs();

for (int i = 0; i < TimeZoneIds.length; i++) {

    TimeZone tz   = TimeZone.getTimeZone(TimeZoneIds[i]);
    String tzName = tz.getDisplayName(tz.inDaylightTime(date),TimeZone.SHORT);

    if(fileTimeZone.equals(tzName)){
        timezoneLongName = TimeZoneIds[i];
        break;
    }
}

if(timezoneLongName != null && !timezoneLongName.isEmpty() && !timezoneLongName.trim().isEmpty() && timezoneLongName.length() != 0){
    TimeZone.setDefault(TimeZone.getTimeZone(timezoneLongName));
} 

虽然MDT时区有多个条目,但它解决了我的问题在第一次匹配时没有任何问题的问题。我已经测试了CDT,MDT和CDT时区的代码,它运行得非常好。谢谢伙计!!!

Although there are more than one entries for "MDT" timezone but it resolves my problem without any problem at first match itself. I have tested code on CDT, MDT and CDT timezones and it worked really well.Thanks Guys!!!

这篇关于Java在运行时设置时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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