java 在java的simpledateformat中强制4位数年份

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3108561/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 00:24:19  来源:igfitidea点击:

forcing 4 digits year in java's simpledateformat

javadateformatting

提问by dr jerry

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

我想使用格式为“yyyymmdd”的 simpleDateFormat 验证和解析日期这也允许 100624,它被解析为第 10 年(Julius Ceasar 死后 54 年)。日期也将类似于 1970,所以我不想用 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()?

我想知道有没有办法使用 SimpleDateFormat 强制使用四位数的年份格式?我即将进行正则表达式测试,但也许有一种聪明的方法来使用 (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?

根据代码的要求,事情变得越来越复杂,我的研究只有一半。使用的格式是 yyyy-MM-dd(它来自一个变量,它有一个错误的 javadoc)。但是,正如下面的回答所示, yyyyMMdd 确实强制使用了四年数字。所以我的问题改为如何为“yyyy-MM-dd”格式强制使用四位数年份。为什么“yyyyMMdd”表现不同?

    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

打印 0040-12-14

采纳答案by Joachim Sauer

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

只需使用yyyyMMdd(注意:大写 M 用于表示月份,否则您正在解析分钟!)然后检查年份是否大于某个截止日期(例如,在解析出生日期时,更大的 1800 是一个安全的赌注,当解析大于或等于当前年份的即将到来的日期的日期会很好)。

回答by Jon Skeet

Hmm. I suspect you should be using "MM" instead of "mm" to start with... but "100624" doesn't parse anyway when I try it - even in lenient mode:

唔。我怀疑你应该使用“MM”而不是“mm”开始......但是“100624”在我尝试时无论如何都不会解析 - 即使在宽松模式下:

import java.util.*;
import java.text.*;

public class Test
{
    public static void main(String[] args) throws Exception
    {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        format.setLenient(true);
        tryParse(format, "100624");
        format.setLenient(false);
        tryParse(format, "100624");
    }

    static void tryParse(DateFormat format, String text)
    {
        try
        {
            Date date = format.parse(text);
            System.out.println("Parsed " + text + " to " + date);
        }
        catch (ParseException pe)
        {
            System.out.println("Failed to parse " + text);
        }
    }
}

(And even using "mm" instead of "MM" it stillfails to parse.)

(即使使用“mm”而不是“MM”,它仍然无法解析。)

Prints:

印刷:

Failed to parse 100624
Failed to parse 100624

Perhaps you could show the code which ismanaging to parse this?

也许你可以显示哪些代码管理解析这个?

回答by Jesper

Try calling setLenient(false);on the SimpleDateFormatobject - that will make it use more strict rules for parsing (otherwise it will try to be "smart" if the input string doesn't exactly match the format). For example:

尝试调用setLenient(false);上的SimpleDateFormat对象-这将使其使用更严格的规则,用于分析(否则它会尽可能地“智能”如果输入字符串不完全匹配格式)。例如:

DateFormat df = new SimpleDateFormat("yyyyMMdd");
df.setLenient(false);

And ofcourse, months is MM, not mm.

当然,月是MM,不是mm

回答by Maciej Dragan

There is no easy way for this. If you're saying that dates can be like 1970 the main question would be what 700624 means - 1970 or 2070? You should either implement some cutoff date like Joachim proposed or move entirely to 4 digits year.

对此没有简单的方法。如果你说日期可以像 1970 年,那么主要的问题是 700624 是什么意思——1970 年还是 2070 年?您应该像 Joachim 提议的那样实施一些截止日期,或者完全改用 4 位数年份。

回答by Ugo Uchegbu

Well it is quite straight and forward. Follow these simple steps:

嗯,这是非常直接和向前的。请按照以下简单步骤操作:

Step 1:

步骤1:

try {
    String dates = "40-12-14";
    String patterns = "yy-MM-dd";
    SimpleDateFormat format3 = new SimpleDateFormat(patterns);``
    java.util.Date dates1 = format3.parse(dates);

    SimpleDateFormat sdfDates = new SimpleDateFormat("dd/MM/yyyy");

    String strDate1 = sdfDate.format(dates1);
    System.out.println("Date1: " + strDate1);

}
catch(ParseException e){
    e.printStackTrace();
}

This will output:

这将输出:

Date1: 14/12/1940