【问题标题】:Get year format from a given Date format从给定的日期格式获取年份格式
【发布时间】:2013-05-18 17:13:22
【问题描述】:

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

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

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

【问题讨论】:

  • 日期字符串“01/02/03”中的年份是什么?见thisthat

标签: java date format


【解决方案1】:

请务必注意,“年份格式”的概念仅适用于 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"。根据上面代码中的注释,请注意这只会提取 first 年份格式。如果您需要提取多种格式,您只需要稍微不同地使用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。所以这是我写的代码
  • SimpleDateFormat df= new SimpleDateFormat("mmddyyyy");最终模式 YEAR_PATTERN=Pattern.compile("y+"); MatchResult m=YEAR_PATTERN.matcher(df.toPattern()).toMatchResult();字符串年份格式; if(m!=null) yearFormat = m.group();否则 yearFormat = "空"; System.out.println("年份模式为=====>"+yearFormat);
  • 我在线程 "main" java.lang.IllegalStateException 中遇到异常:未找到匹配项
  • 很抱歉。尝试更新的代码。像往常一样,魔鬼在细节中。 :P
  • 感谢您的及时回复
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-17
  • 2016-11-29
  • 1970-01-01
相关资源
最近更新 更多