Java 用于管理 SimpleDateFormat 的 CodenameOne 实现的 X、XX、XXX(ISO 时区)格式案例的代码

Java code for managing X, XX, XXX (ISO timezone) format cases for CodenameOne implementation of SimpleDateFormat

我使用 CodenameOne 跨平台工具创建了一个应用程序。它使用自己的 Java classes 版本。 在许多情况下,存在那些 CN1 classes 没有解决的边缘情况。目前还不清楚它是多少。这是由于 API 版本问题或其他开发问题。

现在我必须使用 CN1 SimpleDateFormat class。我检查了一下,有些情况我不得不自己处理。

我用单引号管理文字,u 参数,现在我必须处理时区

X, XX, XXX

参数。

我不知道是否应该解决其他情况。我的应用程序与 Android 或 Oracle 示例兼容,所以对我来说已经足够了,因为我至少可以重现示例案例。

X, XX, XXX 格式应对应 -08; -0800; -08:00

所以

我创建了这段代码,它依赖于 Z 时区参数,对应于 -0800

String format=completeFormatString;

Date date= new Date();
Calendar calendar = Calendar.getInstance(); //CN1 Calendar implementation
calendar.setTime(date);

String timeZoneFormat="Z";
SimpleDateFormat timeZoneDateFormat = new SimpleDateFormat(timeZoneFormat);
String timeZone=timeZoneDateFormat.format(calendar);

String timeZoneLastPart=timeZone.substring(timeZone.length()-2);
String timeZoneFirstPart=timeZone.substring(0,timeZone.length()-2);

format=StringUtil.replaceAll((format,"XXX",timeZoneFirstPart+":"+timeZoneLastPart);
format=StringUtil.replaceAll(format,"XX",timeZoneFirstPart+timeZoneLastPart);
format=StringUtil.replaceAll(format,"X",timeZoneFirstPart);

是否正确,将其放入我的应用程序是否安全?

很遗憾你被臭名昭著的麻烦和早已过时的 SimpleDateFormat class 困住了。以下是它在 Oracle Java 11.

中的行为示例
    for (String zid : new String[] { "Etc/UTC", "America/Inuvik", "Asia/Katmandu" }) {
        System.out.format("%-14s", zid);
        for (String formatPattern : new String[] { "Z", "X", "XX", "XXX" }) {
            SimpleDateFormat sdf = new SimpleDateFormat(formatPattern);
            sdf.setTimeZone(TimeZone.getTimeZone(ZoneId.of(zid)));
            System.out.format(" %-6s", sdf.format(0L));
        }
        System.out.println();
    }

输出为:

Etc/UTC        +0000  Z      Z      Z     
America/Inuvik -0800  -08    -0800  -08:00
Asia/Katmandu  +0530  +05    +0530  +05:30

对于非零偏移量,它似乎按照您编写代码时预期的方式工作。在我看来,您还需要从模式字母 Z 构建偏移量零的特殊情况 +0000 因为在这种情况下,模式字母大写 X 会产生 Z(对于零时区或祖鲁时区)无论您使用 XXX 还是 XXX.