0

I have a requirement to give a user a bonus on their birthday. My approach is this, I want to take the user's date of birth, then compare their date of birth with the current system date, and if the DOB.day and DOB.Month is equal to the system.day and system.month then award the user a bonus. Does anyone have any idea how I could go about this in Java?

Any suggestions will be helpful, I'm new to Java but I think this is very possible no?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • Does this answer your question? [Comparing user input date with current date](https://stackoverflow.com/questions/19726115/comparing-user-input-date-with-current-date) – Mady Daby Apr 15 '21 at 23:39
  • 2
    You can use the MonthDay class: https://docs.oracle.com/javase/8/docs/api/java/time/MonthDay.html – assylias Apr 16 '21 at 00:48
  • @MadyDaby No. That qusetion includes year. This OP wants to compare only month and day of month, so that question won’t work. – Ole V.V. Apr 16 '21 at 04:22

1 Answers1

1

java.time.MonthDay

As assylias already commented, use MonthDay. It’s from java.time, the modern Java date and time API, and there are links at the bottom. To demonstrate:

    ZoneId zone = ZoneId.of("Europe/Simferopol");
    
    MonthDay today = MonthDay.now(zone);
    
    DateTimeFormatter dobFormatter = DateTimeFormatter.ofPattern("M/d");
    String userInput = "4/16";
    MonthDay dateOfBirth = MonthDay.parse(userInput, dobFormatter);
    
    if (dateOfBirth.equals(today)) {
        System.out.println("Happy birthday " + dateOfBirth);
    }

Output today (April 16):

Happy birthday --04-16

A MonthDay, as the name says, is a month and day of month, so without a year. It’s exactly good for birthdays, anniversaries and the like. The MonthDay prints in ISO 8601 format, or you may format it using the same formatter or a different one. If your users prefer to enter in a different format, for example 16-4, change the format pattern string accordingly.

Beware that users born on February 29 (in a leap year) won’t get their bonus very often, which will be seen as unfair and may be illegal in some jurisdictions. So you will probably want to treat those as a special case. Use if (dateOfBirth.equals(MonthDay.of(Month.FEBRUARY, 29))). In non-leap years you may want to give the bonus on the last day of February or the first day of March, for example.

Links

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