java 4位数,在java的简单格式中强制4位数字

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").

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()?

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);

}

Which prints 0040-12-14

解决方案

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).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值