google/gson · error · IllegalArgumentException

Unknown DateFormat style

Error message

Unknown DateFormat style: ${timeStyle}

What it means

PreJava9DateFormatProvider.getTimePartOfDateTimePattern maps a DateFormat style constant to a Java-8-era US time pattern. Recognized values: SHORT, MEDIUM, FULL, LONG (FULL and LONG share the same pattern). Any other value falls through to the default branch and throws IllegalArgumentException (PreJava9DateFormatProvider.java:60).

Solutions

  1. Use only the recognized DateFormat constants: SHORT, MEDIUM, LONG, FULL.
  2. Validate the int at the boundary: if (style < 0 || style > 3) throw new IllegalArgumentException(...).
  3. Provide an explicit SimpleDateFormat pattern via GsonBuilder.setDateFormat("h:mm:ss a") to avoid the style mapping entirely.

Example fix

// before
DateFormat df = PreJava9DateFormatProvider.getUsDateTimeFormat(dateStyle, timeStyle); // timeStyle == 7
// after
int timeStyle = (timeStyleRaw < 0 || timeStyleRaw > 3) ? DateFormat.SHORT : timeStyleRaw;
DateFormat df = PreJava9DateFormatProvider.getUsDateTimeFormat(dateStyle, timeStyle);
Defensive patterns

Strategy: validation

Validate before calling

if (timeStyle < DateFormat.SHORT || timeStyle > DateFormat.FULL) throw new IllegalArgumentException("bad time style");

Type guard

static boolean isKnownStyle(int s) { return s >= 0 && s <= 3; }

Try / catch

try { PreJava9DateFormatProvider.getUsDateTimeFormat(dateStyle, timeStyle); } catch (IllegalArgumentException e) { /* invalid style */ }

Prevention

When it happens

Trigger: Calling PreJava9DateFormatProvider.getUsDateTimeFormat with a timeStyle outside {SHORT, MEDIUM, LONG, FULL}, e.g. an unvalidated int from configuration or a mis-typed constant.

Common situations: Config-driven date formatting where the time style int comes from a properties file or DB; passing DateFormat.DEFAULT (== MEDIUM coincidentally, but other invalid ints fail); library code reading style ints without validation.

Related errors


AI-assisted analysis of google/gson@310ac341f2 (2026-08-10). Data as JSON: /api/errors/6b7b8f1eaeebfa29. Report an issue: GitHub.

Appendix: source

Thrown at gson/src/main/java/com/google/gson/internal/PreJava9DateFormatProvider.java:61

        return "MMMM d, yyyy";
      case DateFormat.FULL:
        return "EEEE, MMMM d, yyyy";
      default:
        throw new IllegalArgumentException("Unknown DateFormat style: " + dateStyle);
    }
  }

  private static String getTimePartOfDateTimePattern(int timeStyle) {
    switch (timeStyle) {
      case DateFormat.SHORT:
        return "h:mm a";
      case DateFormat.MEDIUM:
        return "h:mm:ss a";
      case DateFormat.FULL:
      case DateFormat.LONG:
        return "h:mm:ss a z";
      default:
        throw new IllegalArgumentException("Unknown DateFormat style: " + timeStyle);
    }
  }
}

View on GitHub (pinned to 310ac341f2)