Android time zone string to local time

Accessing the background interface today, I suddenly found that the server returned time: 2022-11-11T12:02:07.000+00:00

Angrily, he went to the backstage and told the other party that he could not return to the time zone. Obviously, the time I uploaded did not uninstall the time zone, why did the returned time become like this.

Backstage answer: The previous section has been connected and cannot be modified. In an instant, it felt like ten thousand alpacas rushed over.

Well, only I can modify it.

SimpleDateFormat has provided us with different conversion methods, the comparison table is as follows:
    //HH显示的是24小时制,hh显示的是12小时制
    时间格式                            对应时间
    yyyy-MM-dd                         1969-12-31
    yyy-MM-dd                          1970-01-01
    yyyy-MM-dd HH:mm                   1969-12-31 16:00
    yyyy-MM-dd HH:mm                   1970-01-01 00:00
    yyyy-MM-dd HH:mmZ                  1969-12-31 16:00-0800
    yyyy-MM-dd HH:mmZ                  1970-01-01 00:00+0000
    yyyy-MM-dd HH:mm:ss.SSSZ           1969-12-31 16:00:00.000-0800
    yyyy-MM-dd HH:mm:ss.SSSZ           1970-01-01 00:00:00.000+0000
    yyyy-MM-dd'T'HH:mm:ss.SSSZ         1969-12-31T16:00:00.000-0800
    yyyy-MM-dd'T'HH:mm:ss.SSSZ         1970-01-01T00:00:00.000+0000
   

 main function code

//服务器时区格式
SimpleDateFormat simple1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.000+00:00");
//需要展示时间格式
SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

Different time formats can be changed according to project requirements.

The complete method method is attached

public String timezoneToTime(String timezone) {
        //服务器时区格式
        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.000+00:00");
        //需要展示时间格式
        SimpleDateFormat toSimple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 本地时区
        Calendar nowCal = Calendar.getInstance();
        TimeZone localZone = nowCal.getTimeZone();
        // 设定SDF的时区为本地
        toSimple.setTimeZone(localZone);

        // 设置时间区域为GMT
        simple.setTimeZone(TimeZone.getTimeZone("GMT"));
        try {
            //解析GMT时间
            Date fromDate = simple.parse(timezone);
            // GMT转当前时区时间
            String toTime = toSimple.format(fromDate);
            return toTime;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "yyyy-MM-dd HH:mm:ss";
    }

Supongo que te gusta

Origin blog.csdn.net/x158454996/article/details/127819738
Recomendado
Clasificación