如何在Java中验证日期(仅当前日期或之后) [英] How can i validate date (only current date or after) in Java

查看:69
本文介绍了如何在Java中验证日期(仅当前日期或之后)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为用户输入的日期添加输入验证.有一个startDate和endDate.startDate必须是当前日期或更高日期.endDate必须等于startDate之后的OR.

I need to add input validation for Dates entered by users. There is a startDate and endDate. The startDate needs to be current date or later. The endDate needs to be equal to OR after the startDate.

我使用的日期格式为YYYY-MM-dd

The date format i am using is YYYY-MM-dd

已经确认该日期是正确的日期

Already validating that the date is a proper date

在请求类中,我们目前正在使用javax.validation,如下所示:

In the request class we currently are using javax.validation like this:

@Pattern(regex = CommmonRegexp.DATE, message = "INVALID_FIELD")

我该如何编辑它以适应我所需的约束?

How do i edit this to fit my needed constraints?

我需要什么:验证两个日期的输入,确保startDate仅接受当前日期或更晚,并且endDate仅接受比startDate晚的日期

What i need: validate input for both dates making sure startDate only accepts current date or later, and endDate accepts only dates later than startDate

推荐答案

您应该使用 java.time 对Java中的日期进行操作.以下是一种根据需要验证日期的有效方法.您可以根据需要更改格式.您还可以使用许多其他有用的方法.将此方法称为 validateDates("2019-03-03","2019-04-03")

You should use java.time to operate on dates in java. Following is a working method to validate the date as you require. You can change the format as you require. There are a bunch of other useful methods that you can use. call this method as validateDates("2019-03-03","2019-04-03")

public static boolean validateDates(String start, String end) {
    try {
        DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate startDate = LocalDate.parse(start, dateFormat);
        LocalDate endDate = LocalDate.parse(end, dateFormat);
        LocalDate current = LocalDate.now();
        return (startDate.isEqual(current) || startDate.isAfter(current)) && endDate.isAfter(startDate);
    }catch(DateTimeParseException ex) {
        ex.printStackTrace();
    }
    return false;
}

更新

您可以根据需要使用预定义或自定义的 DateTimeFormatter s.您可以通过 JavaDoc,以获取有关DateTimeFormatters的详细信息,并通过此博客获得示例.

You can use predefined or custom DateTimeFormatters as per your need. You can go through this JavaDoc for details on DateTimeFormatters in detail and through this blog for examples.

This and this are some good-reads about how to use zone-ids with date-times.

这篇关于如何在Java中验证日期(仅当前日期或之后)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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