Home > front end >  How to convert utc timezone to specific time zone by dayjs?
How to convert utc timezone to specific time zone by dayjs?

Time:11-30

I have UTC timezone DateTime 2022-11-28T23:58:29.670Z And want to get DateTime 2022-11-29T03:58:29.670Z 4 hours. and at the end, I need 2022-11-29

I tried several approaches createdAt is 2022-11-28T23:58:29.670Z

const tz = 'America/Santo_Domingo';
const withtz = dayjs(createdAt).tz(tz);
const withtzday = withtz.format('YYYY-MM-DD');

And additional explanation. The user saves an item and I store it in UTC. But this item should show up in a specific timezone for this branch. So when I filter it by day I need to filter by createdBy but by particular timezone.

CodePudding user response:

I've not been able to reproduce the problem. Following the Dayjs documentation outputs the correct time UTC and for Santo Domingo.

However, the question seems to assume that Santo Domingo is UTC 4 when it is actually UTC-4. So the hour calculation is: 23:58 - 4:00 = 19:58 on the same day. And this calculation matches the output from Dayjs.

Snippet

let createdAt = '2022-11-28T23:58:29.670Z';

const tz = 'America/Santo_Domingo';
let utcdate = dayjs(createdAt);
const tzdate = utcdate.tz(tz);

console.log(
  'Created UTC:  ', utcdate.toISOString(), 
  '\nSanto Domingo:', tzdate.format('YYYY-MM-DDTHH:mm:ss'),
  '\nSanto Domingo:', tzdate.format('YYYY-MM-DD')
);
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/plugin/utc.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/plugin/timezone.js"></script>
<script>
  dayjs.extend(window.dayjs_plugin_utc);
  dayjs.extend(window.dayjs_plugin_timezone);  
</script>

  • Related