我想使用格式为yyyymmdd"的 simpleDateFormat 验证和解析日期这也允许 100624,它被解析为 10 年(朱利叶斯·凯撒去世 54 年后).日期也会是 1970 年,所以我不想与 SimpleDateFornat("yymmdd") 达成一致.
I want to validate and parse dates using a simpleDateFormat with the format "yyyymmdd" This also allows 100624, which is parsed to the year 10 (54 years after Julius Ceasar died). The dates will also be something like 1970, so I don't want to settle with SimpleDateFornat("yymmdd").
我想知道有没有办法使用 SimpleDateFormat 强制使用四位数的年份格式?我即将提前进行正则表达式测试,但也许有一种聪明的方法可以使用 (Simple)DateFormat()?
I'm wondering is there a way to force a four digit year format using the SimpleDateFormat? I'm close to do a regexp test upfront but maybe there is a smart way to use the (Simple)DateFormat()?
根据要求的代码,事情变得越来越复杂,我的研究只完成了一半.使用的格式是 yyyy-MM-dd 开始(它来自一个变量,它有一个错误的 javadoc).但是,正如下面的答案所示 yyyyMMdd 确实强制使用四年数字.所以我的问题变成了如何为yyyy-MM-dd"格式强制一个四位数的年份.为什么yyyyMMdd"表现不同?
As requested the code, things are getting more complicate and my research was half. The Format used was yyyy-MM-dd to start with (it came from a variable, which had a wrong javadoc). However as indicated in an answer below yyyyMMdd does force a four year digit. So my question is changed to How to force a four digit year for the "yyyy-MM-dd" format. And why does "yyyyMMdd" behave different?
public void testMaturity() {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.setLenient(false);
System.out.println(" " + sdf.format(sdf.parse("40-12-14")));
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
sdf.setLenient(false);
System.out.println(" " + sdf2.format(sdf2.parse("401214")));
fail();
} catch (ParseException pe) {
assertTrue(true);
}
打印 0040-12-14
Which prints 0040-12-14
直接使用yyyyMMdd(注意:大写M表示月份,否则你正在解析分钟!),然后检查年份是否大于某个截止日期(例如,当解析出生日期时,大于 1800 是一个安全的选择,当解析大于或等于当前年份的即将到来的日期时会很好).
Simply use yyyyMMdd (note: upper case M is used to indicate month, otherwise you're parsing minutes!) and then check if the year is greater some cutoff date (for example, when parsing birth dates, greater 1800 is a safe bet, when parsing dates for upcomming dates greater than or equal the current year would be good).
这篇关于在 java 的 simpledateformat 中强制 4 位数年份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
解析 ISO 8601 字符串本地日期时间,就像在 UTC 中Parsing an ISO 8601 string local date-time as if in UTC(解析 ISO 8601 字符串本地日期时间,就像在 UTC 中一样)
如何将公历字符串转换为公历?How to convert Gregorian string to Gregorian Calendar?(如何将公历字符串转换为公历?)
Java:GregorianCalendar 的最大值和最小值是什么/在哪Java: What/where are the maximum and minimum values of a GregorianCalendar?(Java:GregorianCalendar 的最大值和最小值是什么/在哪里?)
1582 年 10 月 15 日之前日期的日历到日期转换.公历Calendar to Date conversion for dates before 15 Oct 1582. Gregorian to Julian calendar switch(1582 年 10 月 15 日之前日期的日历到日期转换
java日历setFirstDayOfWeek不起作用java Calendar setFirstDayOfWeek not working(java日历setFirstDayOfWeek不起作用)
Java:获取当前星期几的值Java: getting current Day of the Week value(Java:获取当前星期几的值)