如何在Java中进行日期格式验证

huangapple go评论69阅读模式
英文:

How to make date formate validation in Java

问题

以下是您要翻译的代码部分:

public static boolean validateJavaDate(String strDate) {

    /*
     * Set preferred date format, For example MM-dd-yyyy, MM.dd.yyyy,dd.MM.yyyy etc.
     */
    SimpleDateFormat sdfrmt = new SimpleDateFormat("yyyy-MM-dd");
    sdfrmt.setLenient(false);
    try {
        Date javaDate = sdfrmt.parse(strDate);
        System.out.println(strDate + " is valid date format");
    }
    catch (ParseException e) {
        System.out.println(strDate + " is Invalid Date format");
        return false;
    }
    return true;
}
英文:

I want to make date format validation. It should be yyyy-mm-dd and to achieve my requirement I followed below code but it's not working.

My input request should be either 2020-13-08 or 2020-13-08T23:00:00Z but it should be 2020-08-13 or 2020-08-13T23:00:00Z

public static boolean validateJavaDate(String strDate) {

		/*
		 * Set preferred date format, For example MM-dd-yyyy, MM.dd.yyyy,dd.MM.yyyy etc.
		 */
		SimpleDateFormat sdfrmt = new SimpleDateFormat("yyyy-mm-dd");
		sdfrmt.setLenient(false);
		try {
			Date javaDate = sdfrmt.parse(strDate);
			System.out.println(strDate + " is valid date format");
		}
		catch (ParseException e) {
			System.out.println(strDate + " is Invalid Date format");
			return false;
		}
		return true;
	}

答案1

得分: 3

It's better to use the new java.time package instead

public static boolean validateJavaDate(String strDate) {
    if (strDate == null || strDate.isEmpty()) { //for completeness 
        System.out.println("Given value can not be null or empty");
        return false;
    }

    DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE;
    try {
        formatter.parse(strDate);
        System.out.println(strDate + " is valid date format");
        return true;
    }
    catch (DateTimeParseException e) {
        System.out.println(strDate + " is Invalid Date format");
        return false;
    }
}

If the goal is to validate both date strings with and without time we can extract the actual parsing to a private method and call it with different formatters

private static boolean formatDate(String string, DateTimeFormatter formatter) {
    try {
        formatter.parse(string);
        return true;
    } catch (DateTimeParseException e) {
        return false;
    }

}
public static boolean validateJavaDate(String strDate) {
    if (strDate == null || strDate.isEmpty()) { //for completeness 
        System.out.println("Given value can not be null or empty");
        return false;
    }

    boolean isValid = formatDate(strDate, DateTimeFormatter.ISO_LOCAL_DATE);
    if (!isValid) {
        isValid = formatDate(strDate, DateTimeFormatter.ISO_DATE_TIME);
    }

    if (isValid) {
        System.out.println(strDate + " is valid date format");
    } else {
        System.out.println(strDate + " is Invalid Date format");
    }

    return isValid;
}
英文:

It's better to use the new java.time package instead

public static boolean validateJavaDate(String strDate) {
    if (strDate == null || strDate.isEmpty()) { //for completeness 
        System.out.println("Given value can not be null or empty");
        return false;
    }

    DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE;
    try {
        formatter.parse(strDate);
        System.out.println(strDate + " is valid date format");
        return true;
    }
    catch (DateTimeParseException e) {
        System.out.println(strDate + " is Invalid Date format");
        return false;
    }
}

If the goal is to validate both date strings with and without time we can extract the actual parsing to a private method and call it with different formatters

private static boolean formatDate(String string, DateTimeFormatter formatter) {
    try {
        formatter.parse(string);
        return true;
    } catch (DateTimeParseException e) {
        return false;
    }

}
public static boolean validateJavaDate(String strDate) {
    if (strDate == null || strDate.isEmpty()) { //for completeness 
        System.out.println("Given value can not be null or empty");
        return false;
    }

    boolean isValid = formatDate(strDate, DateTimeFormatter.ISO_LOCAL_DATE);
    if (!isValid) {
        isValid = formatDate(strDate, DateTimeFormatter.ISO_DATE_TIME);
    }

    if (isValid) {
        System.out.println(strDate + " is valid date format");
    } else {
        System.out.println(strDate + " is Invalid Date format");
    }

    return isValid;
}

答案2

得分: 1

yyyy-mm-dd 匹配小时中的分钟(mm 部分),这就是验证通过的原因。将其替换为 yyyy-MM-dd 以匹配月份。请参阅 https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/SimpleDateFormat.html 以查看 SimpleDateFormat 的文档。

英文:

yyyy-mm-dd matches minutes in hour (the mm) part, that's why the validation passes. Replace it with yyyy-MM-dd to match the month instead. See https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/SimpleDateFormat.html for the documentation of SimpleDateFormat.

答案3

得分: 0

以下是翻译好的代码部分:

对于另一种方法您可以手动执行

类似这样的代码

public boolean isDate(String format)
{   
  int year = format.subString(0,3); //必须验证subString是整数
  int month = format.subString(5,6); //同样
  int day = format.subString(8,9); //同样

  if(month <= 12 && month >= 1)
  {
     //有效
     if(day <= 31 && day >= 1)
     {
        if(String.valueOf(format.chatAt(4)).equals("-") && String.valueOf(format.chatAt(7)).equals("-"))
        return true;
     }
  }
  .
 }

请注意,我已经保留了原始代码中的标记和格式。

英文:

For other hand you can do it manual.

Somethink like that

public boolean isDate(String format)
{   
  int year = format.subString(0,3); //You must validate that the subString is Integer
  int month = format.subString(5,6); //Same
  int day = format.subString(8,9); //Same


  if(month <= 12 && month >= 1)
  {
     //is valid
     if(day <= 31 && day >= 1)
     {
        if(String.valueOf(format.chatAt(4)).equals("-") && String.valueOf(format.chatAt(7)).equals("-")
        return true;
     }
  }
  .
 }

huangapple
  • 本文由 发表于 2020年8月13日 21:48:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/63396644.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定