0

我有一个本地化的日期格式。我想只检索 Java 中的年份格式。

因此,如果给我 mmddyyyy,我想提取 yyyy。如果给我 mmddyy,我想提取 yy。

我找不到使用 SimpleDateFormat、Date、Calendar 等类获取该信息的方法。

4

1 回答 1

0

需要注意的是,“年份格式”的概念仅适用于SimpleDateFormat. (无论如何,在默认的 JDK 中。)更具体地说,SimpleDateFormat它是 JDK 提供的唯一DateFormat实现,它使用“格式字符串”的概念,您可以从中提取年份格式;Date其他实现使用从 a到 a 的更不透明的映射String。出于这个原因,您所要求的只是在SimpleDateFormat类上明确定义(同样,在DateFormat股票 JDK 中可用的实现中)。

但是,如果您使用的是SimpleDateFormat,则可以使用正则表达式提取年份格式:

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.

正则表达式看起来很奇怪,因为它必须忽略日期格式字符串的“花式”引用部分中发生的任何 y,例如"'Today''s date is 'yyyy-MM-dd". 根据上面代码中的注释,请注意,这只提取了第一年的格式。如果您需要提取多种格式,您只需要Matcher稍微不同地使用:

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;
}
于 2013-05-18T17:49:55.953 回答