开发者

How can a DateFormat parse an exact date in java (like DateTime.ParseExact in .NET)?

This question is raised by the following code:

DateFormat DF = new SimpleDateFormat("yyyyMMdd");
String dateString = "20110133";
System.out.println(DF.parse(dateString));
// Wed Feb 02 00:00:00 CET 2011

The parse method transformed Jan 33 to Feb 02. Is there a way t开发者_如何学JAVAo throw an Exception if the dateString does not represent a real date?

Just like DateTime.ParseExact in .NET.


Try doing this

DF.setLenient(false);

javadoc reference


You can use the setLenient(boolean) method of the DateFormat class to tell it not to be lenient (i.e. accept and then convert) with dates that aren't valid.


java.time

The accepted answer uses legacy date-time API which was the correct thing to do using the standard library in 2011 when the question was asked. In March 2014, java.time API supplanted the error-prone legacy date-time API. Since then, it has been strongly recommended to use this modern date-time API.

The java.time API is based on ISO 8601 and for basic format i.e. yyyyMMdd, it comes with a predefined formatter, DateTimeFormatter.BASIC_ISO_DATE.

Using this predefined formattter, try to parse your string to a LocalDate and catch the exception, if any, to understand the cause.

Demo using java.time API:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

public class Main {
    public static void main(String[] args) {
        String[] samples = { "20221123", "20110133", "20110131", "20110229", "20110228" };
        for (String dateString : samples) {
            try {
                System.out.println("============================");
                System.out.println(
                        dateString + " parsed to " + LocalDate.parse(dateString, DateTimeFormatter.BASIC_ISO_DATE));
            } catch (DateTimeParseException e) {
                System.err.println(e.getMessage());
            }
        }
    }
}

Output:

============================
20221123 parsed to 2022-11-23
============================
Text '20110133' could not be parsed: Invalid value for DayOfMonth (valid values 1 - 28/31): 33
============================
20110131 parsed to 2011-01-31
============================
Text '20110229' could not be parsed: Invalid date 'February 29' as '2011' is not a leap year
============================
20110228 parsed to 2011-02-28

Learn more about the modern Date-Time API from Trail: Date Time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜