It's important to note that the concept of a "year format" only really applies to SimpleDateFormat
. (In the default JDK, anyway.) More specifically, SimpleDateFormat
is the only DateFormat
implementation provided by the JDK that uses the concept of a "format string" that you can pull out a year format from; the other implementations use more opaque mappings from a Date
to a String
. For this reason, what you're asking for is only well-defined on the SimpleDateFormat
class (again, among the DateFormat
implementations available in the stock JDK).
If you're working with a SimpleDateFormat
, though, you can just pull the year format out with regular expressions:
SimpleDateFormat df=(something);
final Pattern YEAR_PATTERN=Pattern.compile("^(?:[^y']+|'(?:[^']|'')*')*(y+)");
Matcher m=YEAR_PATTERN.matcher(df.toPattern());
String yearFormat=m.find() ? m.group(1) : null;
// If yearFormat!=null, then it contains the FIRST year format. Otherwise, there is no year format in this SimpleDateFormat.
The regular expression looks so strange because it has to ignore any y's that happen in "fancy" quoted parts of the date format string, like "'Today''s date is 'yyyy-MM-dd"
. Per the comment in the code above, note that this only pulls out the first year format. If you need to pull out multiple formats, you'll just need to use the Matcher
a little differently:
SimpleDateFormat df=(something);
final Pattern YEAR_PATTERN=Pattern.compile("\\G(?:[^y']+|'(?:[^']|'')*')*(y+)");
Matcher m=YEAR_PATTERN.matcher(df.toPattern());
int count=0;
while(m.find()) {
String yearFormat=m.group(1);
// Here, yearFormat contains the count-th year format
count = count+1;
}