Java set timezone at runtime

随声附和 提交于 2019-12-06 12:03:51

MDT is not the timezone key, it is the short display name of the timezone, so TimeZone.getTimeZone("MDT") would return default time zone which is GMT. The keys for Mountain Time are MST,MST7MDT etc. So, you need to identify the key of the timezone. Please note there are many different keys for the same short display name e.g. for MDT shortName there are keys with US/Mountain, US/Arizona, SystemV/MST7MDT, Navajo, Mexico/BajaSur, MST7MDT and MST.

Theres no timezone called MDT, it is MST7MDT. Use:

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

Also see Java's java.util.TimeZone

Use the setTimeZone(...) method from the Calendar class.

dirtyhandsphp

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

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!!!

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!