0

I have date strings like Sun May 10 2020 13:00:00 GMT-0800 (Pacific Standard Time) and 2020/05/10 13:00:00. I would like to retrieve the hour from these string in 24 hour format (in this case it would be, 13).

I have tried something like new Date('Sun May 10 2020 13:00:00 GMT-0800 (Pacific Standard Time)').getHours() but that first converts the hour to system's current timezone and then returns the hour. Instead, I need to be able to retrieve the literal hour from variously formatted date strings such as the two above examples.

Edit: Obviously the above is not the correct approach, what I'm asking is, is there a universal way to parse the hour out of a date string, whether it be the above two examples or others, and without regex?

Bryan M
  • 1
  • 1
  • 1
    You can't pass random strings to the Date constructor and hope it will parse them successfully, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) In both OP examples it's fairly straight forward to parse the strings to get the time part and extract the hours without converting them to Date objects, e.g. `'Sun May 10 2020 13:00:00 GMT-0800 (Pacific Standard Time)'.match(/\d\d:\d\d:\d\d/)[0].split(/:/)[0]` – RobG May 13 '20 at 00:37
  • @RobG thanks, I appreciate what I tried was not correct. However it would work if the mechanism that converts the string to your local hour as a date object didn't happen. So clear JavaScript has the ability to parse a number of different strings into date objects and then get that converted hour. Why shouldn't one expect that there is a way to prevent the conversion. I'd like to avoid introducing a bunch of bugs with edge-cases using regex as the strings can be any number of formats. Surely there must be some way to perhaps get JS to not convert then parse, but just parse. – Bryan M May 13 '20 at 08:55
  • The built–in parser is implementation dependent except for the 2 formats supported by ECMAScript. It only takes one value: the string to parse and has no options. Strings are parsed to an offset from the epoch so are essentially UTC, not local. Dates don't store any information about how they were created, they are just a time value. It's all in the answers at the link in my first comment, also [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date). – RobG May 13 '20 at 20:33

0 Answers0