Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

java - Calculating timezone from GMT value - Android


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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...