从 SimpleDateFormat 解析到 Date 不起作用?

Parsing from SimpleDateFormat to Date not working?

SimpleDateFormat df = new SimpleDateFormat();
Date lastLogin = null;
try {
    String troubleChild = lineScanner.next();
    lastLogin = df.parse(troubleChild);
} catch (ParseException e) {
    System.out.println("ohnoes");
}

您好,我对使用日期函数还很陌生,但遇到了一个问题。我有一个文件被解析成各种变量,它们都可以工作,除了这个我永远无法得到它,所以它通过了 try/catch 子句我已经查找了类似的问题,但其中 none 工作在我的代码上。(我输入的日期格式为:周一,10 月 30 日 22:20:11 GMT 2017)请给我一些帮助,谢谢!

解决方案:java.time

请不要为早已过时的 类 DateSimpleDateFormat 烦恼。而是使用 java.time,现代 Java 日期和时间 API 也称为 JSR-310:

    DateTimeFormatter dtf 
            = DateTimeFormatter.ofPattern("E, MMM d H:mm:ss z uuuu", Locale.UK);
    String inputDate = "Mon, Oct 30 22:20:11 GMT 2017";
    ZonedDateTime lastLogin = ZonedDateTime.parse(inputDate, dtf);
    System.out.println(lastLogin);

这会打印

2017-10-30T22:20:11Z[GMT]

由于日期和时间可能有多种不同的文本格式,我使用格式模式字符串来指定您的特定格式。关于您可以使用哪些字母,以及使用 1 个、3 个或 4 个相同字母会有什么区别,请参阅 the documentation。请注意格式模式字符串区分大小写。

问题:SimpleDateFormat

您使用了无参数 SimpleDateFormat 构造函数。我阅读 the documentation 的方式为您提供了您所在地区的默认日期格式。如果您的 JVM 是 运行 UK locale,我相信格式会像 28/11/17 10:57 — 与您尝试解析的输入格式不太一样。您可以使用 System.out.println(df.format(new Date())); 来找出答案。通常使用的 SimpleDateFormat 构造函数是 SimpleDateFormat(String, Locale) 以便您可以再次提供格式模式字符串和语言环境。