Tung Vo
Tung Vo

Reputation: 2549

java 8 new Date/Time API get first day of year

With java 7 we can get first day of year by

    Calendar currentCal = Calendar.getInstance();
    currentCal.set(Calendar.DAY_OF_YEAR, 1);
    currentCal.set(Calendar.MONTH, 0);
    currentCal.set(Calendar.DAY_OF_MONTH, 1);
    currentCal.set(Calendar.HOUR_OF_DAY, 0);
    currentCal.set(Calendar.MINUTE, 0);
    currentCal.set(Calendar.SECOND, 0);
    currentCal.set(Calendar.MILLISECOND, 0);
    //currentCal.getTime();

How to get first day of year like this in java 8 new Date/Time API ?

Upvotes: 0

Views: 3456

Answers (2)

Anonymous
Anonymous

Reputation: 86173

    LocalDate firstDayOfThisYear = Year.now(ZoneId.systemDefault()).atDay(1);
    System.out.println(firstDayOfThisYear);

Output whan I ran just now:

2021-01-01

The Year class didn’t have a corresponding representation in the old date-time API but is handy for cases like this one.

As you may already know, a LocalDate is a date without time of day. Since you asked for the first day of year, I assumed that this class would be appropriate for you. With the old classes we would have been forced to also decide a time of day. With java.time we’re not. If you do need a time of day, you will probably want to convert to a ZonedDateTime (OffsetDateTime, Instant and LocalDateTime are other options depending on your precise requirements).

You need to choose a time zone since New Year doesn’t happen at the same instant in all time zones. In corner cases, if you use an incorrect time zone, your result will be a full year off. I was assuming that the default time zone of your JVM is fine. It may well be safer to use a time zone ID, as in for example ZoneId.of("Asia/Ho_Chi_Minh").

Upvotes: 6

Elliott Frisch
Elliott Frisch

Reputation: 201409

There are a number of ways you could do it, I would start with LocalDateTime and the current year and then the first day of the first month. Like,

LocalDateTime first = LocalDateTime.of(LocalDate.now().getYear(), 1, 1, 0, 0);

Upvotes: 3

Related Questions