Java的数据格式在所有场景下都无法正常工作。

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

Java data format is not working in all scenarios

问题

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

public static boolean validateDateFormat(String strDate) {
    SimpleDateFormat sdfrmt = new SimpleDateFormat("yyyy-MM-dd");
    sdfrmt.setLenient(false);
    try {
        sdfrmt.parse(strDate);
    }
    catch (ParseException e) {
        return false;
    }
    return true;
}

请注意,这只是代码的翻译部分,不包括问题和其他内容。如果您有任何进一步的问题或需要帮助,请随时提问。

英文:

What is the mistake I did in my below code? If we do not pass date format like yyyy-MM-dd, it should throw parse error and it should return false but below one scenario not working

  • 2020-08-19-->This is working fine and returning true
  • 2020-19-08-->This is working fine and returning false
  • 20-08-19-->This should return false. It is not working and returning true

I am not understanding why third scenario getting failed.

Clarification: I am asking: if we pass input: 20-19-08, it should return false, right? But its returning true. My problem is, if I pass 20 instead of 2020, it should return false.

Code

	public static boolean validateDateFormat(String strDate) {
		SimpleDateFormat sdfrmt = new SimpleDateFormat("yyyy-MM-dd");
		sdfrmt.setLenient(false);
		try {
			sdfrmt.parse(strDate);
		}
		catch (ParseException e) {
			return false;
		}
		return true;
	}

答案1

得分: 2

20-19-08 不符合格式,因为年份未指定为四位数字(尽管您使用的格式化工具可以将20和2020都识别为有效年份,但不是同一年),而且根据格式字符串,您的月份值将显示为19,这是无效的。

英文:

20-19-08 does not follow the format because the year is not specified as a four digit number (though the formatter you are using will recognize both 20 and 2020 as valid years, just not the same year) and your month value according to the format string will come up as 19, which is not valid.

答案2

得分: 1

你没有在 catch 块中抛出异常。因此它不会抛出任何异常,只会简单地返回 false。要获取实际异常,请将其抛出或使用 printStackTrace() 打印。

这种方法应该适用于两种情况:

import java.util.*;
import java.text.SimpleDateFormat;

public class Main {
    public static void main(String[] args) {

        String ss = "20-19-08";
        if (validateDateFormat(ss)) {
            System.out.println("SUCCESS");
        } else {
            System.out.println("ERROR");
        }

    }

    public static boolean validateDateFormat(String strDate) {
        SimpleDateFormat sdfrmt = new SimpleDateFormat("yyyy-dd-MM");
        sdfrmt.setLenient(false);
        try {
            Date date = sdfrmt.parse(strDate);
            System.out.println("Formatted Date :: " + date);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}

测试结果:

输入:20-19-08
输出:

Formatted Date :: Mon Aug 19 00:00:00 UTC 20
SUCCESS

输入:2020-19-08
输出:

Formatted Date :: Wed Aug 19 00:00:00 UTC 2020
SUCCESS

英文:

You are not throwing the exception in catch block. hence it does not throw anything simply retyurn false. To get the actual exception throw it or printStackTrace() it.

This approach should be working for both conditions :

import java.util.*;
import java.text.SimpleDateFormat;


public class Main{
	public static void main(String[] args) {

        String ss = "20-19-08";
        if(validateDateFormat(ss)){
            System.out.println("SUCCESS");
        }else {
            System.out.println("ERROR");
        }
        
	}
	
	public static boolean validateDateFormat(String strDate) {
        SimpleDateFormat sdfrmt = new SimpleDateFormat("yyyy-dd-MM");
        sdfrmt.setLenient(false);
        try {
            Date date = sdfrmt.parse(strDate);
            System.out.println("Formatted Date :: "+date);
            return true;
        }
        catch (Exception e) {
            return false;
        }
    }
}

Test results :

Input : 20-19-08
Output : 

Formatted Date :: Mon Aug 19 00:00:00 UTC 20
SUCCESS

Input : 2020-19-08
Output :

Formatted Date :: Wed Aug 19 00:00:00 UTC 2020
SUCCESS

答案3

得分: 1

## java.time

我认为 `SimpleDateFormat` 无法为您提供所需的验证这与该类因存在问题而闻名并且已经过时无论如何您都不应该使用它我建议您对所有日期工作使用现代的 Java 日期和时间 APIjava.time它可以很好地验证日期字符串请使用 `DateTimeFormatter.ISO_LOCAL_DATE`。

    public static boolean validateDateFormat(String strDate) {
        try {
            DateTimeFormatter.ISO_LOCAL_DATE.parse(strDate);
        }
        catch (DateTimeParseException e) {
            return false;
        }
        return true;
    }

试试看

        String candidate = "20-08-19";
        boolean valid = validateDateFormat(candidate);
        System.out.format("Is %s valid? %s%n", candidate, valid);

输出为

>     Is 20-08-19 valid? false

我们也可以尝试一些其他字符串

>     Is 2020-13-19 valid? false
>     Is 2020-08-19 以及不应出现在此处的其他一些文本 valid? false

以及一个有效的示例

>     Is 2020-08-19 valid? true

## 为什么您的代码不起作用

> 我不明白为什么第二种情况失败了有人可以帮帮我吗

这是 `SimpleDateFormat` 解析数字的方式从文档中可以得知

>  - **年份**如果格式化程序的 `Calendar` 是格里高利历将应用以下规则
>     - 
>     - 对于解析如果模式字符的数量超过2个则年份会被直接解释而不考虑数字的位数
> 所以在使用模式 "MM/dd/yyyy""01/11/12" 被解析为公元12年1月11日
>     - 

我认为这个例子与您的情况相当吻合即使您在格式模式字符串中使用 `yyyy`,`SimpleDateFormat` 也可以将 `20` 解析为公元20年这解释了为什么不会引发异常从而导致您的方法返回 true

## 链接

[Oracle 教程日期时间](https://docs.oracle.com/javase/tutorial/datetime/) 解释了如何使用 java.time。
英文:

java.time

I don’t think SimpleDateFormat is able to give you the validation you are asking for. Which is just the same since that class is notoriously troublesome and long outdated. You shouldn’t use it anyway. I recommend that you use java.time, the modern Java date and time API, for all of your date work. And it validates your date string nicely. Use DateTimeFormatter.ISO_LOCAL_DATE.

public static boolean validateDateFormat(String strDate) {
try {
DateTimeFormatter.ISO_LOCAL_DATE.parse(strDate);
}
catch (DateTimeParseException e) {
return false;
}
return true;
}

Try it out:

	String candidate = "20-08-19";
boolean valid = validateDateFormat(candidate);
System.out.format("Is %s valid? %s%n", candidate, valid);

Output is:

> Is 20-08-19 valid? false

We can try some other strings too:

> Is 2020-13-19 valid? false
> Is 2020-08-19 and some more text that should not be here valid? false

And a valid one:

> Is 2020-08-19 valid? true

Why didn’t your code work?

> i am not understanding why second scenario getting failed can some one
> help me please

This is the way SimpleDateFormat parses numbers. From the documentation:

> - Year: If the formatter's Calendar is the Gregorian calendar, the following rules are applied.
> - …
> - For parsing, if the number of pattern letters is more than 2, the year is interpreted literally, regardless of the number of digits.
> So using the pattern "MM/dd/yyyy", "01/11/12" parses to Jan 11, 12
> A.D.
> - …

I think the example matches your situation pretty nicely. Even though you use yyyy in the format pattern string, SimpleDateFormat is happy to parse 20 as year 20 AD. This would explain why no exception is thrown, which in turn causes your method to return true.

Oracle tutorial: Date Time explaining how to use java.time.

huangapple
  • 本文由 发表于 2020年8月22日 00:41:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/63526858.html
匿名

发表评论

匿名网友

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

确定