首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >验证以3种不同格式从用户处获取的日期

验证以3种不同格式从用户处获取的日期
EN

Stack Overflow用户
提问于 2022-03-19 04:33:45
回答 2查看 48关注 0票数 0

当这三种日期格式作为输入时,是否有一种方法来验证它们?

  • "03/03/2000“
  • "03-03-2000“
  • “2000年3月3日”

我设法想出了一个前2的正则表达式。

代码语言:javascript
复制
\\d{2}/\\d{2}/\\d{4}
\\d{2}-\\d{2}-\\d{4}

我使用regex的每一种方法都有一个很大的缺陷。regex只检查格式,而不检查日期是否为有效日期。有没有办法检查这3种日期格式的格式和有效性?

对于这个应用程序来说,考虑后缀是很重要的。

EN

回答 2

Stack Overflow用户

发布于 2022-03-19 05:47:06

下面所做的是测试,看看给定的格式是否可以将String解析为LocalDateLocalDateTime。如果可以(两者都可以),它将将格式化结果与原始输入进行比较,以确保(因为日期/时间处理非常有趣)。

这样做的目的不仅是确定这些值是否在指定格式内,还在于验证它们是否实际上是有效的日期/时间值,因为99/99/0000是有效的格式,但不是有效的日期( SimpleDateFormat‍♂️除外)。

解析和比较不区分大小写。

代码语言:javascript
复制
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.DateTimeParseException;
import java.util.Locale;

public final class Main {
    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        String[] formats = new String[] { 
            "dd/MM/yyyy",
            "dd-MM-yyyy",
            "d MMMM yyyy"
        };

        String[] values = new String[] {
            "03/03/2000",
            "03-03-2000",
            "3rd march 2000"
        };

        for (String value : values) {
            String fixedValue = value.replaceAll("(?<=\\d)(st|nd|rd|th)", "");
            boolean isValid = isValid(formats, fixedValue, Locale.ENGLISH);
            System.out.println(value + " is valid = " + isValid);
        }
    }

    public boolean isValid(String[] formats, String value, Locale locale) {
        for (String format : formats) {
            if (isValidDate(format, value, locale) || isValidDateTime(format, value, locale)) {
                return true;
            }
        }
        return false;
    }

    public boolean isValid(String format, String value, Locale locale) {
        return isValidDate(format, value, locale) || isValidDateTime(format, value, locale);
    }

    public boolean isValidDateTime(String format, String value, Locale locale) {
        try {
            DateTimeFormatter fomatter = new DateTimeFormatterBuilder()
                    .parseCaseInsensitive()
                    .appendPattern(format)
                    .toFormatter(locale);
            LocalDateTime ldt = LocalDateTime.parse(value, fomatter);
            return ldt.format(fomatter).equalsIgnoreCase(value);
        } catch (DateTimeParseException | java.time.temporal.UnsupportedTemporalTypeException exp) {
            return false;
        }
    }

    public boolean isValidDate(String format, String value, Locale locale) {
        try {
            DateTimeFormatter fomatter = new DateTimeFormatterBuilder()
                    .parseCaseInsensitive()
                    .appendPattern(format)
                    .toFormatter(locale);
            LocalDate ld = LocalDate.parse(value, fomatter);
            return ld.format(fomatter).equalsIgnoreCase(value);
        } catch (DateTimeParseException | java.time.temporal.UnsupportedTemporalTypeException exp) {
            return false;
        }
    }
}

哪种输出

代码语言:javascript
复制
03/03/2000 is valid = true
03-03-2000 is valid = true
3rd march 2000 is valid = true

ps:谢谢Dev Parzival的正则表达式,这节省了很多时间

票数 3
EN

Stack Overflow用户

发布于 2022-03-19 05:08:14

使用SimpleDateFormat验证

使用SimpleDateFormat格式化日期不支持后缀(stndrdth),因此如果字符串中存在它们,则必须替换它们。

使用SimpleDateFormat格式化

SimpleDateFormat是一个具体的类,用于以区分区域设置的方式格式化和解析日期.它允许格式化(日期->文本)、解析(文本->日期)和规范化。

代码语言:javascript
复制
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

class MainClass{
    public static void main(String ... $){
        System.out.println(isValidDate("03/03/2000"));
        System.out.println(isValidDate("03-03-2000"));
        System.out.println(isValidDate("3rd march 2000"));
    }
    public static boolean isValidDate(String str){
        boolean match = false;
        try{
            Date date =new SimpleDateFormat("dd/MM/yyyy").parse(str.replaceAll("(?<=\\d)(st|nd|rd|th)", ""));
            return true;
        }catch(ParseException e){
            //System.out.println(e);
            match=false;
        }
        try{
            Date date =new SimpleDateFormat("dd-MM-yyyy")
                .parse(str.replaceAll("(?<=\\d)(st|nd|rd|th)", ""));
            return true;
        }catch(ParseException e){
            //System.out.println(e);
            match=false;
        }
        try{
            Date date =new SimpleDateFormat("d MMMM yyyy")
                .parse(str.replaceAll("(?<=\\d)(st|nd|rd|th)", ""));
            return true;
        }catch(ParseException e){
            //System.out.println(e);
            match = false;
        }
        return match;
    }
}

使用DateTimeForFormatter格式化

代码语言:javascript
复制
import java.time.format.DateTimeFormatter;
import java.time.LocalDate;
import java.time.format.DateTimeParseException;
import java.time.format.DateTimeFormatterBuilder;

class MainClass{
    public static void main(String ... $){
        System.out.println(isValidDate("03/03/2000"));
        System.out.println(isValidDate("03-03-2000"));
        System.out.println(isValidDate("3rd march 2000"));
    }
    public static boolean isValidDate(final String str){
        try{
            DateTimeFormatter formatter =
                DateTimeFormatter.ofPattern("dd/MM/yyyy");
            LocalDate date = LocalDate.parse(str, formatter);
            return true;
        }catch(DateTimeParseException e){
            //System.out.println(e);
        }
        try{
            DateTimeFormatter formatter =
                DateTimeFormatter.ofPattern("dd-MM-yyyy");
            LocalDate date = LocalDate.parse(str, formatter);
            return true;
        }catch(DateTimeParseException e){
            //System.out.println(e);
        }
        try{
            DateTimeFormatter formatter =
                new DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern("d MMMM yyyy").toFormatter();
            LocalDate date = LocalDate.parse(str.replaceAll("(?<=\\d)(st|nd|rd|th)", ""), formatter);
            return true;
        }catch(DateTimeParseException e){
            //System.out.println(e);
        }
        return false;
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71535387

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档