在java的简单格式中强制4位数字 [英] forcing 4 digits year in java's simpledateformat

查看:832
本文介绍了在java的简单格式中强制4位数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用格式为yyyymmdd的simpleDateFormat验证和解析日期
这也允许100624,它解析为10年(Julius Ceasar去世后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的四位数年份格式?我很接近做前期的正则表达式测试,但也许有一个聪明的方式来使用(简单的)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的简单格式中强制4位数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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