Search code examples
javascripttemporalecmascript-temporal

How to adjust the readonly properties for Temporal ZonedDateTime?


Looking into using a polypill for javascript temporal.

If I have Temporal.now, how do I adjust that to the 8th hour of today for example. Do I parse out the properties and make a new ZonedDateTime or is there a better way?


Solution

  • Generally, use the with() method. It creates a new Temporal.ZonedDateTime which is a copy of the original, but any properties present on the method's argument override the ones already present on the original.

    So, if you already have an object zdt, and you want the hour to be 8, use

    zdt.with({ hour: 8 })
    // e.g. 2022-03-13T08:55:59.853514471-07:00[America/Vancouver]
    

    Although, I wasn't sure from your description if this is exactly what you want; you might get today at 08:55:59.something, as above. If you want the time to be 8 o'clock, use the withPlainTime() method, which creates a new object and replaces all of the time-related properties at once:

    zdt.withPlainTime({ hour: 8 })
    // e.g. 2022-03-13T08:00:00-07:00[America/Vancouver]
    

    or, if you literally want the 8th hour of today, beware that that is technically not always 08:00, for example if your time zone has a daylight saving time transition that day (as in this example, America/Vancouver did on 2022-03-13; the clock skipped forward an hour during the night). Although this seems unlikelier than the other two possibilities, if the 8th hour of the day is what you need, use the startOfDay() method* and add() 8 hours:

    zdt.startOfDay().add({ hours: 8 })
    // e.g. 2022-03-13T09:00:00-07:00[America/Vancouver]
    

    *currently described in the documentation as a read-only property, but that is a mistake