简体   繁体   English

如何在Java中检查不同的日期格式

[英]how to check different date formats in java

I am getting different date formats below dd-MM-yyyy,dd/MM/yyyy , yyyy-MM-dd , yyyy/MM/dd 我在dd-MM-yyyy,dd/MM/yyyyyyyy-MM-ddyyyy/MM/dd下面得到了不同的日期格式

SimpleDateFormat sm1 = new SimpleDateFormat("dd-MM-yyyy");
String date = "01-12-2013";
System.out.println("Date 1 is "+sm1.parse(date));
date = "2013-12-01";
System.out.println("Date 1 is "+sm1.parse(date));

the same simple date format gives the below result eventhough date format is wrong(ie:-2013-12-01).Below the results. 即使日期格式错误(即:-2013-12-01),相同的简单日期格式也会产生以下结果。

 Date 1 is Sun Dec 01 00:00:00 IST 2013
 Date 1 is Sun Jun 05 00:00:00 IST 7

您需要setLenient(false)才能使parse()方法在无法分析的情况下throw ParseException

I have tried Jigar Joshi's answer. 我已经尝试过吉加尔·乔希的答案。 ==========================code======================================= ==========================代码======================= ================

SimpleDateFormat sm1 = new SimpleDateFormat("dd-MM-yyyy");
sm1.setLenient(false);
String date = "01-12-2013";
System.out.println("Date 1 is "+sm1.parse(date));
date = "2013-12-01";
System.out.println("Date 1 is "+sm1.parse(date));

=========================Result======================================== =========================结果======================== ================

Date 1 is Sun Dec 01 00:00:00 CST 2013
Exception in thread "main" java.text.ParseException: Unparseable date: "2013-12-01"
    at java.text.DateFormat.parse(DateFormat.java:337)
    at workflow.Test.main(Test.java:14)

Your date format is dd-MM-yyyy . 您的日期格式为dd-MM-yyyy That means the parser is expecting some day, month, and year format. 这意味着解析器期望的是日,月和年格式。

From the SimpleDateFormat documentation : the number of pattern letters in a Number type formatter is the minimum . SimpleDateFormat文档中Number类型格式化程序中的模式字母Number是最小的 So, while 2013 wouldn't make sense in our mind, it fits within the formatter's bounds. 因此,虽然我们认为2013没有意义,但它符合格式化程序的范围。

You have provided 2013-12-01 as to fit into that format. 您已提供2013-12-01以适合该格式。 What it appears the formatter is doing is providing December 1 (insert timezone here), and then adding 2,013 days to it. 格式化程序正在执行的工作是提供12月1日(在此处插入时区),然后再添加2,013天。

That turns out to be June 6, 7 AD . 原来是公元6月6日 There's some wiggle room for your timezone (I'm not sure which of the five timezones IST represents is actually yours ). 您的时区有一些摆动的空间(我不确定IST代表的五个时区中的哪个实际上是您的 )。

So, believe it or not...the formatter is correct. 因此,信不信由你……格式化程序是正确的。 Be very careful as to what kind of format you specify or allow in your dates! 特别注意日期中指定或允许的格式!

If you don't want that parsed, then specify setLenient(false) on your instance of sm1 . 如果您不希望对其进行解析,则在sm1实例上指定setLenient(false)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM