0

I'm trying to do this without adding moment js to my project but it seems more difficult than I'd like.

if I get a date that's formatted as : "2021-07-19T12:15:00-07:00"

Is there an efficient way to have it formatted as: "12:15 pm"

regardless of where me and my browser are located?

I've gotten as far as some other answers with no luck, for example:

var date = new Date('2021-07-19T12:15:00-07:00')
var userTimezoneOffset = date.getTimezoneOffset() * 60000;
new Date(date.getTime() - userTimezoneOffset);

Thanks!

Best Dev Tutorials
  • 452
  • 2
  • 6
  • 22
  • Does this answer your question? [How to format a JavaScript date?](https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date) – zr0gravity7 Jul 09 '21 at 14:49
  • Does this answer your question? [How to extract only time from iso date format in javascript?](https://stackoverflow.com/questions/47607666/how-to-extract-only-time-from-iso-date-format-in-javascript) – 0stone0 Jul 09 '21 at 14:53
  • @zr0gravity7 Unfortunately no – Best Dev Tutorials Jul 09 '21 at 15:39
  • @0stone0 Unfortunately no – Best Dev Tutorials Jul 09 '21 at 15:40
  • Treating random timestamps as local is problematic in places where daylight saving is observed. On the change into DST, there is 30 minutes to 1 hour that doesn't exist, and on change back there is a similar period that exists twice. So you need to implement a rule to cover those cases as different implementations may resolve the issue differently. – RobG Jul 09 '21 at 23:52

1 Answers1

0

You could use Date.toLocaleTimeString() to format the time, this will give you the time in the local timezone, if we remove the UTC offset.

There are other options available here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat

let timestampWithUTCOffset = "2021-07-19T12:15:00-07:00";
let timestampWithoutUTCOffset = timestampWithUTCOffset.substr(0,19);

console.log( { timestampWithUTCOffset , timestampWithoutUTCOffset });
let dt = new Date(timestampWithoutUTCOffset);
console.log('Time of day:', dt.toLocaleTimeString('en-US', { timeStyle: 'short' }))
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40