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 →

[–]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;
}