Moment JS: Get the date and time from the lost timezone string

I have some formatted datetime string, like this Fri Sep 18th 2020 05:52:20.
When I use momentJS to convert theme to datetime => Fail. Because that's invalid datetime format.
So, how can I convert them to datetime with a timezone (ie: 'Euro/Paris').

1 answer

  • answered 2020-10-16 04:45 chiliNUT

    If your date format isn't a standard format, you can specify a format string for it as the 2nd argument

    (https://momentjs.com/docs/#/parsing/string-format/)

    The format string for: 3 letter day of week, 3 letter month, ordinal day, 4 digit year, 24 hour time format with leading 0 is:

    ddd MMM Do YYYY HH:mm:ss
    

    You can specify a timezone with moment().tz

    moment.tz(
        moment(
            "Fri Sep 18th 2020 05:52:20",
            "ddd MMM Do YYYY HH:mm:ss"
        ), "Europe/Paris")
        .format("YYYY-MM-DD HH:mm:ss z"); // "2020-09-18 12:52:20 CEST"
    

    Also please bear in mind RobG's comment on timezone

    the string is parsed as local, it's the output that is shifted to the specified timezone. So the resulting timestamp values are dependent on the host system timezone settings