我有一個本地化的日期格式。我想檢索Java中的年份格式。從給定的日期格式獲取年份格式
所以,如果我給mmddyyyy我想提取yyyy。 如果我給了mmddyy,我想提取yy。
我找不到使用SimpleDateFormat,Date,Calendar等類獲取該信息的方法。
我有一個本地化的日期格式。我想檢索Java中的年份格式。從給定的日期格式獲取年份格式
所以,如果我給mmddyyyy我想提取yyyy。 如果我給了mmddyy,我想提取yy。
我找不到使用SimpleDateFormat,Date,Calendar等類獲取該信息的方法。
重要的是要注意,「年份格式」的概念只適用於SimpleDateFormat
。 (無論如何,在默認的JDK中)。更具體地說,SimpleDateFormat
是由JDK提供的唯一DateFormat
實現,它使用「格式字符串」的概念,您可以從中抽出年份格式;其他實現使用更多不透明映射,從Date
到String
。出於這個原因,你要求的只是在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;
}
我應該總是得到一個SimpleDateFormat。所以這是我寫的代碼 – user2397334
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
我不會在這裏寫代碼:-( – user2397334
什麼是在日期字符串「01/02/03」的一年?請參閱[this](http://stackoverflow.com/q/15010210/155813)和[that](http://stackoverflow.com/q/4216191/155813)。 – mg007