Search code examples
javascriptangulartypescriptlodash

How to convert time to specific string?


I'm working with a date that looks like this:

Mon Feb 04 2019 15:57:02 GMT-0700 (Mountain Standard Time)

and I'm trying to convert it to this:

2019-02-04T15:57:02.000Z

but for some reason my code always adds 7 hours and ends up being like this:

"2019-02-05T22:57:02.000Z"

Can anyone tell me what I'm doing wrong? Thanks a lot in advance!

Here's my code:

new Date(myTime as string).toISOString();

Solution

  • I'd use Moment.js, which is a decent date parsing and formatting library. To get what you're looking for, you'd use a statement like:

    console.log(moment
      .parseZone(
        "Mon Feb 04 2019 15:57:02 GMT-0700 (Mountain Standard Time)",
        "ddd MMM DD YYYY HH:mm:ss 'GMT'ZZ") // the format of the string presented
      .local()
      .format('YYYY-MM-DDTHH:mm:ss')); // the format of the output
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

    I've broken the single line out into parts so it's a bit easier to read. A few notes:

    • parseZone allows you to parse the "-0700" from the string.
    • local converts the date from the parsed time zone to the current time zone
    • format formats the date.

    The format topic has a list of the formatting tokens used. The Parse > String + Format topic lists the parsing tokens (which are the same as the formatting tokens for the most part).

    Note that the output does not have a "Z" at the end; this is important because without the "Z", it is a local date. With the "Z" you are are actually specifying a date and time that is 7 hours earlier than the one you've been given.