【问题标题】:is there any way to convert the date in java prior to 1970?有什么方法可以在 1970 年之前转换 java 中的日期吗?
【发布时间】:2019-07-11 12:18:58
【问题描述】:

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

【问题讨论】:

  • 我建议你不要使用SimpleDateFormat。这个类是出了名的麻烦和过时。而是使用来自java.time, the modern Java date and time APILocalDateDateTimeFormatter
  • 我相信这里有几个有用的答案:How to convert two digit year to full year using Java 8 time API(当问题不完全相同时)。
  • 使用 Java 8 java.time api,旧日期 api 已损坏。
  • 除了使用过时、不受欢迎的 API 之外,在其中找到 set2DigitYearStart 方法真的那么难吗?
  • 欢迎来到 Stack Overflow。老实说,在我看来,按照 Stack Overflow 标准,这是一个糟糕的问题。它没有显示搜索、研究或其他努力,没有代码,没有最小示例,没有示例输入和输出。我知道你是新来的,所以无论如何我已经提供了答案。学习how to ask a good question需要一点时间。请努力,我相信你会学到的。

标签: java java-8 simpledateformat date-formatting 2-digit-year


【解决方案1】:

java.time

解析输入

控制yymmdd中2位年份解释的方法是通过DateTimeFormatterBuilderappendValueReduced方法。

    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 格式化回字符串。出于这个原因,我还将解析与上面的格式分开。

链接

Oracle tutorial: Date Time 解释如何使用 java.time。

【讨论】:

    猜你喜欢
    • 2011-07-02
    • 1970-01-01
    • 2017-04-28
    • 2013-05-26
    • 1970-01-01
    • 2011-04-29
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    相关资源
    最近更新 更多