Using SimpleDateFormat's “ZZZZZ” (+03:00) for

2019-06-27 11:51发布

问题:

I'm using SimpleDateFormat with format yyyy-MM-dd'T'HH:mm:ssZZZZZ. The expected output is "2014-08-26T13:00:14+03:00". However, "ZZZZZ" is only supported since Android 4.3.

Here is the result:

  • Above 4.3: 2014-08-26T13:00:14+03:00
  • Below 4.3: 2014-08-26T13:00:14+0300

Note that the timezone section is different (03:00 vs 0300)

I have looked at this bug report: http://code.google.com/p/android/issues/detail?id=73209.

Is it possible to get same timezone format in all version like above 4.3? Any suggestions?

回答1:

This is the sort of fix I use.

private static final SimpleDateFormat DATEFORMATRFC3339 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ", Locale.ENGLISH);

public static String formatrfc3339(Date date) {
    if(VersionUtils.isJellyBeanMR2Compatible()) {
        return DATEFORMATRFC3339.format(date);
    }
   return DATEFORMATRFC3339.format(date).replaceAll("(\\d\\d)(\\d\\d)$", "$1:$2");
}


回答2:

This is what I use, no version check:

String result = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZZZZZ").format(calendar.getTime());
//fix up for older Android where ZZZZZ does not include colon
if (!result.substring(result.length() - 3).startsWith(":")) {
    result = result.substring(0, result.length() - 2) + ":" + result.substring(result.length() - 2);
        }
return result;