-1

I need a bad data. And I need that data as Date java type.

String sDate1="29/02/2021";
Date date1=new SimpleDateFormat("dd/MM/yyyy").parse(sDate1,new ParsePosition(0));

As many of you know this does not work it will set 01 MAR as date, because of the Data class checks. Is there any way to trick this checks or avoid them?

Gaj Julije
  • 1,538
  • 15
  • 32

2 Answers2

4

java.time again demonstrating why it's superior in almost every way.

This code

String inputStr = "29/02/2021";
LocalDate date = LocalDate.parse(
    inputStr, DateTimeFormatter.ofPattern("dd/MM/uuuu").withResolverStyle(ResolverStyle.STRICT) 
);

Will throw this exception for that input:

Exception in thread "main" java.time.format.DateTimeParseException: Text '29/02/2021' could not be parsed: Invalid date 'February 29' as '2021' is not a leap year

Without the strict resolver style, it will shift it one day back to Feb 28th.

If you really need a j.u.Date then you can convert it as described here. Better yet, keep it in the superior representation.

Michael
  • 41,989
  • 11
  • 82
  • 128
2

Well, a hack is possible. Whether it fulfils your purpose, only you know.

public class FakeDate extends Date {

    @Override
    public String toString() {
        return "Thu May 35 00:00:00 CET 1931";
    }

}

We may use it in this simple way:

    Date date1 = new FakeDate();
    System.out.println(date1);

Output is, as you may have guessed already:

Thu May 35 00:00:00 CET 1931

Link: Der 35. Mai oder Konrad reitet in die Südsee (in German)

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161