简体   繁体   中英

How to convert a UTC timestamp to a time zone, would you set to the time zone in 'fromISO' or do you prefer 'setZone', or does it matter?

What is the best way to convert a UTC timestamp to a specific time zone using Luxon?

I have a UTC timestamp "YYYY-DD-MMTHH:MM:SSZ"

I've found two ways to convert the UTC timestamp to a time zone; either by specifying the time zone in 'fromISO' or using 'setZone':

const luxonUrl  = 'https://cdnjs.cloudflare.com/ajax/libs/luxon/3.0.3/luxon.min.js';
eval(UrlFetchApp.fetch(luxonUrl).getContentText());

function utctotimezone() {
  const timeZ     = '2022-06-01T20:00:00Z';
  const utctime   = 'UTC';
  const uktime    = 'Europe/London';
  const zISO      = luxon.DateTime.fromISO(timeZ).toISO({suppressMilliseconds: true});
  const utcISO    = luxon.DateTime.fromISO(timeZ, {zone: utctime}).toISO({suppressMilliseconds: true});
  const ukISO     = luxon.DateTime.fromISO(timeZ, {zone: uktime}).toISO({suppressMilliseconds: true});
  const ukzoneutc = luxon.DateTime.fromISO(timeZ, {zone: utctime}).setZone(uktime).toISO({suppressMilliseconds: true});
  console.log(utcISO,' - utcISO\n'+zISO,' - zISO\n'+ukISO,' - ukISO\n'+ukzoneutc,' - uk zone from utc');
}

So to convert a UTC timestamp to a time zone, would you set to the time zone in 'fromISO' or do you prefer 'setZone', or does it matter?

references:

You can use .fromISO() , setting the { zone } parameter to the desired value or use the setZone() method.

We can see they will result in the same value using the .equals() method (Two DateTimes are equal if they represent the same millisecond, have the same zone and location, and are both valid)

It then depends on which approach you prefer personally.

 const { DateTime } = luxon; const zone = 'Europe/London'; const timeZ = '2022-06-01T20:00:00Z'; const dateTime1 = DateTime.fromISO(timeZ, { zone }); const dateTime2 = DateTime.fromISO(timeZ).setZone(zone); console.log('dateTime1:', dateTime1.toISO({suppressMilliseconds: true})) console.log('dateTime2:', dateTime2.toISO({suppressMilliseconds: true})) console.log('Times are equal:', dateTime1.equals(dateTime2))
 .as-console-wrapper { max-height: 100%;important; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/3.0.1/luxon.min.js" integrity="sha512-6ZJuab/UnRq1muTChgrVxJhSgygmL2GMLVmSJN7pcBEqJ1dWPbqN9CiZ6U3HrcApTIJsLnMgXYBYgtVkJ8fWiw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

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