从给定的日期格式获取年份格式

时间:2013-05-18 17:13:22

标签: java date format

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

所以,如果给我mmddyyyy,我想提取yyyy。 如果给我mmddyy,我想提取yy。

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

1 个答案:

答案 0 :(得分:0)

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

如果你正在使用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;
}
相关问题