简体   繁体   中英

Get Day, Month, Year from Java Calendar instance

I have an Instant derived from a Java Calendar , eg c.toInstant() , and now in a different location convert that to a custom Date object that needs a day of the month, month, and year. I tried:

    if (instance.isSupported(ChronoField.DAY_OF_MONTH) && instance.isSupported(ChronoField.MONTH_OF_YEAR) && instance.isSupported(ChronoField.YEAR)) {
      return new com.company.common.Date()
          .setDay(instance.get(ChronoField.DAY_OF_MONTH))
          .setMonth(instance.get(ChronoField.MONTH_OF_YEAR))
          .setYear(instance.get(ChronoField.YEAR));
    }

But when I try to compile ErrorProne throws:

...impl/utils/DateUtils.java:21: error: [TemporalAccessorGetChronoField] TemporalAccessor.get() only works for certain values of ChronoField.
          .setDay(instance.get(ChronoField.DAY_OF_MONTH))
                              ^

I'm not sure why I can't find an answer for this anywhere, but after some searching I came up with nothing helpful -- though I probably missed something.

Instant is only a timestamp - it only provides seconds, millis and nanos.

If you start with a calendar instance in the first place you should be able to simply use

calendar.get(Calendar.YEAR)
calendar.get(Calendar.MONTH)
calendar.get(Calendar.DAY_OF_YEAR)

directly to fetch the date values and skip the conversion to Instant.

If you prefer working with the newer time API you can fetch dates and time from a ZonedDateTime like

    Calendar calendar = Calendar.getInstance();
    ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(calendar.toInstant(), calendar.getTimeZone().toZoneId());

    zonedDateTime.getYear();
    zonedDateTime.getMonthValue();
    zonedDateTime.getDayOfMonth();

I don't see a direct advantage for the example given, but it could be useful if you want to use further functionality of the newer java.util.time API

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM