如何从 Java 中的字符串解析不同的日期格式(常见问题解答)

How to Parse different Date formats from String in Java (FAQ)

我曾多次尝试弄清楚如何解析不同的日期格式。在输入中我们有一些行:

1987-03-23
null
1985-11-29
23-07-2000
17-10-1984

它应该被翻译成俄语(在我的任务中,你可以改变它)格式dd.MM.yyyy和它不匹配的地方画破折号。

我是这样决定的:

public class DateUtil {
public static String validDateString(String strDate) {
final List<String> dateFormats = Arrays.asList("yyyy-MM-dd", "dd-MM-yyyy", "MM-dd- 
yyyy", "MM/dd/yyyy", "dd/MM/yyyy");
SimpleDateFormat sdf;
//Our new format
final String RU_FORMAT = "dd.MM.yyyy";
String output = "-";
//Reviewing for all templates
for (String format : dateFormats) {
    sdf = new SimpleDateFormat(format, new Locale("ru"));
    //Do not try to analyze dates that do not match the format
    sdf.setLenient(false);
    try {
        if (sdf.parse(strDate) != null) {
            Date date = sdf.parse(strDate);
            sdf.applyPattern(RU_FORMAT);
            return sdf.format(date);
        }
        break;
    } catch (ParseException e) {

    }
 }
 //Display line with a dash
 return output;
 }
}

你可以通过这行调用这个方法:

DateUtil.validDateString(input_line);

避免遗留日期时间 classes

旧的 DateCalendarSimpleDateFormat classes 是糟糕的糟糕设计。永远不要使用它们。现在被 java.time classes.

取代

正在解析

首先测试输入字符串是否等于 "null"。

接下来,简单地解析第一种格式 LocalDate.parse( "1987-03-23" ) 并捕获异常。默认处理标准 ISO 8601 格式,因此无需指定格式模式。

最后,定义格式模式 DateTimeFormatter.ofPatten( "dd-MM-uuuu" ) 并用它解析,调用 LocalDate.parse( input , formatter )。异常陷阱。

如果所有这些都失败了,你有意想不到的输入。

生成字符串

手头有 LocalDate 对象后,使用 LocalDate.format 生成一个字符串,其中传递 DateTimeFormatter。您可以定义格式模式,如上所示。或者,您可以调用 DateTimeFormatter.ofLocalizedDatejava.time 自动为您本地化。

搜索堆栈溢出

这已经讲过很多次了。在 Stack Overflow 中搜索这些 class 名称,以查看更多详细信息和更多代码。

我建议使用具有 site:whosebug.com 标准的搜索引擎,因为 Stack Overflow 中的内置搜索功能很弱并且往往会忽略答案,只偏向于问题。

例如,这样做:

https://duckduckgo.com/?q=site%3Awhosebug.com+java+DateTimeFormatter&t=h_&ia=web


关于java.time

java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

要了解更多信息,请参阅 Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310

您可以直接与数据库交换 java.time 对象。使用 JDBC driver compliant with JDBC 4.2 或更高版本。不需要字符串,不需要 java.sql.* classes.

从哪里获得java.time classes?

ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.