How to convert date like '2021-06-01T11:17:00-07:00' to ISO standard? What is this format?
let date = new Date('2021-06-01T11:17:00-07:00');
console.log(date.getHours() " :" date.getMinutes());
I should get 11:17 but I am getting back 23:47
So something going wrong in understanding the correct format of date?
To reverse engineer,
If I convert date my expected date which is "2021-06-01 11:17:00" to IsoString then the value which I get is 2021-06-01T05:47:00.000Z which is not equal to 2021-06-01T11:17:00-07:00
PS - So from comments I got to know this format is in MST which is 7 hours behind UTC
CodePudding user response:
Have you tried using the Vanilla javascript Date class? Should be able to pass that into the constructor and then convert it to the desired format. For example: const date2 = new Date('1995-12-17T03:24:00');
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date
You could also try using the Moment library in Javascript, although many people are trying to move away from this.
CodePudding user response:
The input specifies a time zone, so it specifies a time at which in Salt Lake City it is 11:17. That same moment corresponds to 23:47 in New Delhi, which is your time zone.
So when you tell JavaScript to read the input, it will know it is a specification in Mountain Standard Time (-07:00), and will store the date in UTC. When you output the date as you do, JavaScript will use your locale and output it as 23:47, which is the exact same moment that the input specifies.
If you want the time to output as 11:17, then apparently you don't want to consider that it is a local time in Salt Lake City, but ignore that, and just consider it to be 11:17 in your time zone.
In that case, you should change the input, and remove the time zone specification:
let date = new Date('2021-06-01T11:17:00'); // No time zone specified -> is interpreted as local time
console.log(date.getHours() " :" date.getMinutes());
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
If the input string is variable, you can strip the time zone by keeping only the first 19 characters of the input before passing it to the Date
constructor.
But be aware that when you strip the time zone, you actually change the time specification in the input to a different one. It is no longer the same time.