Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
744 views
in Technique[技术] by (71.8m points)

date - forcing 4 digits year in java's simpledateformat

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...