Java 8 LocalDateTime解析无效日期 [英] Java 8 LocalDateTime is parsing invalid date

查看:227
本文介绍了Java 8 LocalDateTime解析无效日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在客户端验证日期,所以我写了以下代码。但是,除了获取异常之外,我正在获得一个适当的日期对象,在2月31日的日期字符串中,这显然是无效的日期。

I wanted to validate date in client side so I wrote the following code. But instead of getting an exception I am getting a proper date object for 31st of February date string, which is clearly an invalid date.

public class Test {

    public static void main(String[] args) {
        String dateFormat = "HH:mm:ss MM/dd/yyyy";
        String dateString = "11:30:59 02/31/2015";
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(dateFormat, Locale.US);
        try {
            LocalDateTime date = LocalDateTime.parse(dateString, dateTimeFormatter);
            System.out.println(date);
        } catch (Exception e) {
            // Throw invalid date message
        }
    }
}

输出:2015-02-28T11:30:59

Output : 2015-02-28T11:30:59

有没有人知道为什么 LocalDateTime 正在解析此日期而不是抛出异常。

Does anyone know why LocalDateTime is parsing this date instead of throwing an exception.

推荐答案

您只需要严格的 ResolverStyle

You just need a strict ResolverStyle.


分析文本字符串分两个阶段。阶段1是根据添加到构建器的字段的基本文本解析。阶段2将解析的字段值对解析为日期和/或时间对象。

Parsing a text string occurs in two phases. Phase 1 is a basic text parse according to the fields added to the builder. Phase 2 resolves the parsed field-value pairs into date and/or time objects. This style is used to control how phase 2, resolving, happens.

示例代码 - 其中 withResolverStyle(ResolverStyle这是重要的变化,连同使用 uuuu 而不是 yyyy (其中 uuuu 是年,yyyy是年代,因此不明确):

Sample code - where withResolverStyle(ResolverStyle.STRICT) is the important change, along with the use of uuuu rather than yyyy (where uuuu is "year" and "yyyy" is "year of era", and therefore ambiguous):

import java.time.*;
import java.time.format.*;
import java.util.*;

public class Test {

    public static void main(String[] args) {
        String dateFormat = "HH:mm:ss MM/dd/uuuu";
        String dateString = "11:30:59 02/31/2015";
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter
            .ofPattern(dateFormat, Locale.US)
            .withResolverStyle(ResolverStyle.STRICT);
        try {
            LocalDateTime date = LocalDateTime.parse(dateString, dateTimeFormatter);
            System.out.println(date);
        } catch (DateTimeParseException e) {
            // Throw invalid date message
            System.out.println("Exception was thrown");
        }
    }
}

这篇关于Java 8 LocalDateTime解析无效日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆