有没有办法将1970年之前的日期转换成java?

有没有办法将1970年之前的日期转换成java?,java,java-8,simpledateformat,date-formatting,2-digit-year,Java,Java 8,Simpledateformat,Date Formatting,2 Digit Year,我想将yymmdd格式的日期转换为YYYYMMDD,但是当使用SimpleDataFormat类时,我得到的是1970年之后的年份,但要求的是1970年之前的年份。java.time 解析输入 DateTimeFormatter fourDigitFormatter = DateTimeFormatter.ofPattern("uuuuMMdd"); String result = date.format(fourDigitFormatter); System.out.p

我想将yymmdd格式的日期转换为YYYYMMDD,但是当使用SimpleDataFormat类时,我得到的是1970年之后的年份,但要求的是1970年之前的年份。

java.time 解析输入

    DateTimeFormatter fourDigitFormatter = DateTimeFormatter.ofPattern("uuuuMMdd");
    String result = date.format(fourDigitFormatter);
    System.out.println(result);
控制
yymmd
中2位数年份解释的方法是通过
DateTimeFormatterBuilder
appendValueReduced
方法

    DateTimeFormatter twoDigitFormatter = new DateTimeFormatterBuilder()
            .appendValueReduced(ChronoField.YEAR, 2, 2, 1870)
            .appendPattern("MMdd")
            .toFormatter();
    String exampleInput = "691129";
    LocalDate date = LocalDate.parse(exampleInput, twoDigitFormatter);
如果提供1870年为基准年,则两位数年份的解释范围为1870年至1969年(因此总是在1970年之前)。根据您的要求提供不同的基准年。另外,除非您确定100年期间的所有输入年份都是预期的和有效的,否则我建议您对解析的日期进行范围检查

格式化和打印输出

    DateTimeFormatter fourDigitFormatter = DateTimeFormatter.ofPattern("uuuuMMdd");
    String result = date.format(fourDigitFormatter);
    System.out.println(result);
本例中的输出为:

19691129

如果输入为
700114
,则输出为:

18700114

使用LocalDate保留日期

与将日期从一种字符串格式转换为另一种格式不同,我建议最好将日期保存在
LocalDate
中,而不是字符串中(就像不在字符串中保存整数值一样)。当程序接受字符串输入时,立即解析为
LocalDate
。仅当需要提供字符串输出时,才将
LocalDate
格式化为字符串。出于这个原因,我还将解析与上面的格式设置分开

链接


解释如何使用java.time。

我建议您不要使用
SimpleDataFormat
。那门课是出了名的麻烦和过时。相反,使用
LocalDate
DateTimeFormatter
,两者都来自。我相信这里有几个有用的答案:(当问题不完全相同时也是如此)。使用Java 8 Java.time api,旧的日期api会被破坏。除了使用过时的、不受欢迎的api,在其中找到
set2DigitYearStart
方法真的有那么难吗?欢迎来到堆栈溢出。我会残酷地告诉你,在我看来,这是一个糟糕的问题,以堆栈溢出标准衡量。它没有显示搜索、研究或其他工作,没有代码,没有最小的示例,没有示例输入和输出。我知道你是新来的,所以我已经提供了一个答案。学习需要一点时间。请努力,我相信你会学到的。