79318598

Date: 2024-12-30 20:58:21
Score: 2
Natty:
Report link

java.time

For new and old readers to this question I strongly recommend that since Java 8 you use java.time, the modern Java date and time API, for your date work. The classes Date, SimpleDateFormat, GregorianCalendar and Calendar hat you were trying to use were troublesome and are fortunately long outdated. So nowadays avoid them.

So it’s about time this question gets answers that demonstrate the use of java.time. There is a good one by Basil Bourque. And here’s my shot.

Interpretation of your question and assumptions

I know that the moderators and some users don’t like reservations and disclaimers like this section and say I should instead ask questions in comments. I’m not sure it works with a 15 years old question that nevertheless still has readers. So I understand from your question that you want a method that does two things:

  1. Validates your input string.
  2. Converts it to a Date.

I assume:

Validate

Using the comment by @Anonymous under the answer by Basil Bourque:

private static final DateTimeFormatter parser
        = DateTimeFormatter.ofPattern("M/d", Locale.ROOT);

/** @throws DateTimeParseException If the string is not valid */
public static MonthDay parseMonthDay(String inString) {
    return MonthDay.parse(inString, parser);
}

Trying it out:

    System.out.println(parseMonthDay("2/29"));

Output:

--02-29

The method rejects for example 2/30, 0/30, 1/32 and 1/31 and some nonsense. Funnily it accepts 001/031.

Convert to a Date object

As I said, you should not use Date. Unless you indispensably need a Date for a legacy API that you cannot upgrade to java.time just now, that is. But! You basically cannot convert your string to a Date. A Date is a point in time and despite the name cannot represent a date, not to mention a day of month without a year. What the troublesome old SimpleDateFormat would do would be take the first moment of the date in its default year of 1970 in the default time zone of the JVM. Since 1970 was not a leap year this implies that 2/29 and 3/1 were both parsed into Sun Mar 01 00:00:00 (your time zone) 1970, that is, you cannot distinguish.

So unless you have specific requirements that I cannot guess, I recommend that you stay with the MonthDay object returned from my method above.

What went wrong in your code?

Link

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

Reasons:
  • Blacklisted phrase (0.5): I cannot
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Unregistered user (0.5):
  • User mentioned (1): @Anonymous
  • Low reputation (1):
Posted by: Manua Kuy