如何使DateFormat猜到世纪? [英] How to make DateFormat guess intended century?

查看:103
本文介绍了如何使DateFormat猜到世纪?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以dd-MM-yy格式将 String 解析为 Date 对象。问题是它试图猜测这个世纪的日期。

I am trying to parse a String in "dd-MM-yy" format to a Date object. The problem is that it tries to guess the century for the date.

当从01到31被指定时,年被解释为2000s(21世纪),32 t0 99被认为是20世纪(20世纪)。

When specified from 01 to 31, year is interpreted as 2000s (21st Century) and 32 t0 99 is considered 1900s (20th Century).

SimpleDateFormat fm =new SimpleDateFormat("dd-MM-yy");
String datestr="21-11-31";
try {
  Date date= fm.parse(datestr);
  System.out.println(date);
} catch (ParseException e) {
}

任何人都可以帮我吗?我怎么能说明我只是在二十一世纪才整齐地工作。我不是完全想要寻找技巧,如操纵字符串或根据条件移动日期。

Can anyone help me? How can I specify that I am only working in the 21st Century neatly. I am not exactly trying to look for tricks like manipulating the string or shifting the date based on the condition.

推荐答案

您可以更改用于使用 set2DigitYearStart() 方法。

You can change the century it uses to interpret 2 digit data entry with the set2DigitYearStart() method.

SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yy");
String aDate = "03/17/40";
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(Calendar.YEAR, 2000);
dateFormat.set2DigitYearStart(cal.getTime());
System.out.println(dateFormat.get2DigitYearStart());
System.out.println(dateFormat.parse(aDate));

将打印2040年3月17日。

Will print March 17, 2040.

这篇关于如何使DateFormat猜到世纪?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆