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

查看:31
本文介绍了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 将解析的字段值对解析为日期和/或时间对象.此样式用于控制阶段 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.STRICT) 是重要的变化,以及使用 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天全站免登陆