2013-05-18 73 views
0

我有一个本地化的日期格式。我想检索Java中的年份格式。从给定的日期格式获取年份格式

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

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

+0

什么是在日期字符串“01/02/03”的一年?请参阅[this](http://stackoverflow.com/q/15010210/155813)和[that](http://stackoverflow.com/q/4216191/155813)。 – mg007

回答

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. 

正则表达式看起来很奇怪,因为它忽略任何Ÿ在这种情况发生“花式”引用日期格式字符串的部分,如"'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; 
} 
+0

我应该总是得到一个SimpleDateFormat。所以这是我写的代码 – user2397334

+0

SimpleDateFormat df = new SimpleDateFormat(“mmddyyyy”); final pattern YEAR_PATTERN = Pattern.compile(“y +”); MatchResult m = YEAR_PATTERN.matcher(df.toPattern())。toMatchResult(); 字符串yearFormat; if(m!= null) \t yearFormat = m.group(); else yearFormat =“empty”; System.out.println(“year pattern is =====”“+ yearFormat); – user2397334

+0

我不会在这里写代码:-( – user2397334