Skip to content

Instantly share code, notes, and snippets.

@pjdietz
Last active March 14, 2024 10:57
Show Gist options
  • Star 22 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save pjdietz/e0545332e2fc67a9a460 to your computer and use it in GitHub Desktop.
Save pjdietz/e0545332e2fc67a9a460 to your computer and use it in GitHub Desktop.
Format a local date as an RFC 3339 date with timezone
function rfc3339(d) {
function pad(n) {
return n < 10 ? "0" + n : n;
}
function timezoneOffset(offset) {
var sign;
if (offset === 0) {
return "Z";
}
sign = (offset > 0) ? "-" : "+";
offset = Math.abs(offset);
return sign + pad(Math.floor(offset / 60)) + ":" + pad(offset % 60);
}
return d.getFullYear() + "-" +
pad(d.getMonth() + 1) + "-" +
pad(d.getDate()) + "T" +
pad(d.getHours()) + ":" +
pad(d.getMinutes()) + ":" +
pad(d.getSeconds()) +
timezoneOffset(d.getTimezoneOffset());
}
@alexnum
Copy link

alexnum commented Jul 18, 2017

Thanks!

@vitto-moz
Copy link

Great!
Thanks

@adeel-ali-atp
Copy link

thanks

@mro
Copy link

mro commented Oct 11, 2021

@zdh-github
Copy link

好厉害

@malihe1991
Copy link

It's very useful

@rhoover
Copy link

rhoover commented Jun 22, 2023

Thank you, works like a charm!

@rein96
Copy link

rein96 commented Sep 5, 2023

Thanks!

Here's the Typescript version 🙇

export function rfc3339(date: Date) {
  function pad(n: number) {
    return n < 10 ? '0' + n : n;
  }

  function timezoneOffset(offset: number) {
    if (offset === 0) {
      return 'Z';
    }

    const sign = offset > 0 ? '-' : '+';
    offset = Math.abs(offset);

    return sign + pad(Math.floor(offset / 60)) + ':' + pad(offset % 60);
  }

  return (
    date.getFullYear() +
    '-' +
    pad(date.getMonth() + 1) +
    '-' +
    pad(date.getDate()) +
    'T' +
    pad(date.getHours()) +
    ':' +
    pad(date.getMinutes()) +
    ':' +
    pad(date.getSeconds()) +
    timezoneOffset(date.getTimezoneOffset())
  );
}


@SowaProgramuje
Copy link

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment