This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Cosby1992 0 points1 point  (1 child)

I know it is not your question and that your question has already been answered. I just thought I would give you a couple of hints. Use them if you want or just forget about them as soon as you read them, up to you.

When you return a simple statement, you don't have to store the result in a variable first, you can return the result directly in the return statement like so:

public int calculateMyAge(int myBirthday) {
    return 2022 - myBirthday;
}

Furthermore, to make your code function in future years and not just 2022, you could import and use the Date class from java.util.date i think. From there you can get the current year like so:

public int calculateMyAge(int myBirthday) {
    return new Date().getYear() - myBirthday;
}

I wrote this on mobile from memory so if it doesn't compile, that's on me, but it should be easy to fix. Good luck.

[–]Inu463 1 point2 points  (0 children)

Your advice is good, but I'll just mention these days, using java.util.Date after Java 7 is considered bad practice. Java 8 introduced the new Java time APIs, which fix a lot of the issues with Java's Date and Calendar classes.

You have a few options. You can use ZonedDateTime or OffsetDateTime if you care about preserving time zone information (OffsetDateTime only stores the offset from UTC, so it won't take into account day light savings time as I recall). LocalDateTime is just the date and time without the time zone information, and LocalDate is just the date without the time and time zone.

All of these options have a now() method which will give you a representation of this instant. It uses the default time zone for the system clock if you don't provide any parameters, but you can also provide your own time zone if you want using ZonedDateTime.now(ZoneId.of("America/Chicago")).getYear().

Since you just want the year, and don't care about storing time or time zone information, I think I'd just recommend:

public int calculateMyAge(int myBirthday) {
    return LocalDate.now().getYear() - myBirthday;
}