-1

I'm trying to pass this props.data.STDout which is a string in this format "2022-04-29 14:05:00" from UTC to local time.

I've tried but it doesn't work, do you have any ideas?

let newDate = new Date(props.data.STDout);
let newDate2 = newDate.toString()

Thank you very much!

Jason Aller
  • 3,541
  • 28
  • 38
  • 38

2 Answers2

-1

Try let newDate2 = newDate.toLocaleString()

Pedro Feltrin
  • 438
  • 2
  • 8
  • Thanks! It works but not as intended. I get the same date but in a different format not having the time difference in to account from "2022-04-29 14:05:00" I get 29/4/2022, 14:05:00, and my local time is UTC+2 wich is what I need Anyway tha nk you very much for your answer :D – Manuel Lope Revilla Apr 29 '22 at 14:24
-1

I got it!

Just needed to add UTC to the original date string, so this is how it looks working perfectly:

let newDate = new Date(`${props.data.STDOut} UTC`);
let newDate2 = newDate.toString();

As props.data.STDOut is a string you should use the literal `${}` to wrap it and be able to add UTC to it, then just parse toString, and done. It might be a more elegant solution, but for now, if it works, it works.

Thanks guys!

  • Produces an invalid date in Safari and Firefox at least. See [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) If you want to parse it as UTC, change "2022-04-29 14:05:00" to "2022-04-29T14:05:00Z" then pass it to the Date constructor. Or parse it manually by splitting into parts and use `new Date(Date.UTC(year, month - 1, day, hour, minute, second))`. – RobG Apr 29 '22 at 19:52
  • Hi @RobG, sorry if I didn't explained myself, I needed a UTC date, passed by props as a string parsed to a local date. But you're right I didn't tried it in other browsers, in Chrome is working, but will check in some other. Thanks for your answer mate! – Manuel Lope Revilla Apr 30 '22 at 20:33
  • It was a comment, not an answer. Modifying the string as suggested and parsing it with the built–in parser does exactly what you want, i.e. it will parse "2022-04-29 14:05:00" as UTC. You can then get a timestamp in the local timezone with `date.toString()`, or in any timezone with `date.toLocaleString(lang, {timeZone: IANALocation})`. – RobG May 01 '22 at 09:01