How to get the timezone offset in GMT(Like GMT+7:0

2020-01-28 00:43发布

I am getting the timezone of a android device using this code

TimeZone tz = TimeZone.getDefault();
String current_Time_Zone = (TimeZone.getTimeZone(tz.getID()).getDisplayName(
                false, TimeZone.SHORT))

But it always return me the timezone like "IST" but i want to get the timezone in GMT like this GMT+7:00.

20条回答
我只想做你的唯一
2楼-- · 2020-01-28 01:22

I've been looking at this too and trying to work out how to apply timezone and DST. Here's my code.

    public long applyGMTOffsetDST(long time) {
    // Works out adjustments for timezone and daylight saving time

    Calendar mCalendar = new GregorianCalendar();  
    TimeZone mTimeZone = mCalendar.getTimeZone();  
    boolean dstBool = mTimeZone.getDefault().inDaylightTime( new Date() );
    // add an hour if DST active

    if (dstBool == true) {
        time = time + secondsPerHour;
    }
    // add offest hours
    int mGMTOffset = mTimeZone.getRawOffset();

    if (mGMTOffset > 0) {
        long offsetSeconds = secondsPerHour * mGMTOffset;
        time = time + offsetSeconds;
    }

    return time;
}

This seems to work, but is there a better way to get the actual time off the device which represents a time that is meaningful and accurate to the user?

查看更多
一夜七次
3楼-- · 2020-01-28 01:22

You can get your custom GMT time from this function from here

  public static String getCurrentDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd hh:mm a zzz");
        Date date = new Date();
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+6:00"));
        return sdf.format(date);
    }
查看更多
登录 后发表回答