Calculating timezone from GMT value - Android

一个人想着一个人 提交于 2019-12-14 03:27:28

问题



In a android form , i am accepting a GMT value(offset) from user such a +5:30 , +3:00.
and from this value , i want to calculate the timeZone that is "India/Delhi".

Any ideas on how to do it ......Plzz


回答1:


If you already have a specific instant in time at which that offset is valid, you could do something like this:

import java.util.*;

public class Test {

    public static void main(String [] args) throws Exception {
        // Five and a half hours
        int offsetMilliseconds = (5 * 60 + 30) * 60 * 1000;
        for (String id : findTimeZones(System.currentTimeMillis(),
                                       offsetMilliseconds)) {
            System.out.println(id);
        }
    }

    public static List<String> findTimeZones(long instant,
                                             int offsetMilliseconds) {
        List<String> ret = new ArrayList<String>();
        for (String id : TimeZone.getAvailableIDs()) {
            TimeZone zone = TimeZone.getTimeZone(id);
            if (zone.getOffset(instant) == offsetMilliseconds) {
                ret.add(id);
            }
        }
        return ret;
    }
}

On my box that prints:

Asia/Calcutta
Asia/Colombo
Asia/Kolkata
IST

(As far as I'm aware, India/Delhi isn't a valid zoneinfo ID.)

If you don't know an instant at which the offset is valid, this becomes rather harder to really do properly. Here's one version:

public static List<String> findTimeZones(int offsetMilliseconds) {
    List<String> ret = new ArrayList<String>();
    for (String id : TimeZone.getAvailableIDs()) {
        TimeZone zone = TimeZone.getTimeZone(id);
        if (zone.getRawOffset() == offsetMilliseconds ||
            zone.getRawOffset() + zone.getDSTSavings() == offsetMilliseconds) {
            ret.add(id);
        }
    }
    return ret;
}

... but that assumes that there are only ever two offsets per time zone, when in fact time zones can change considerably over history. It also gives you a much wider range of IDs, of course. For example, an offset of one hour would include both Europe/London and Europe/Paris, because in summer time London is at UTC+1, whereas in winter Paris is at UTC+1.




回答2:


If I have correctly interpreted your question then try this,

final SimpleDateFormat date=
        new SimpleDateFormat("EEE, MMM d, yyyy hh:mm:ss a z");
date.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("GMT time: " + date.format(currentTime));

In this you can add your offset. see if this helps you.



来源:https://stackoverflow.com/questions/16494929/calculating-timezone-from-gmt-value-android

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