Home > Software design >  How to convert RFC 3339 datetime into regular JavaScript format
How to convert RFC 3339 datetime into regular JavaScript format

Time:11-07

I need to use the Google Calendar service for editing single instances of an event series. The service returns datetime values in RFC 3339 format (like 2022-11-03T21:30:41.043Z), which is hard to process within Google apps script. Is there an easy way feeding it into Utilities.formatDate to convert it (ie yyyy-MM-dd HH:mm)?

Vice versa is plainly done with .toISOString().

CodePudding user response:

You can convert an ISO8601 format date string into a JavaScript Date object directly with the Date constructor. To convert the Date object into a formatted date string, use Utilities.formatDate() with your preferred timezone, like this:

function test() {
  const dateISO8601 = '2022-11-03T21:30:41.043Z';
  const timezone = 'PST';
  const dateString = toDateString_(dateISO8601, timezone);
  console.log(dateString);
}

function toDateString_(dateISO8601, timezone = 'GMT') {
  const date = new Date(dateISO8601);
  return Utilities.formatDate(date, timezone, 'yyyy-MM-dd HH:mm');
}
  • Related