Devmix
Devmix

Reputation: 1868

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();

Upvotes: 0

Views: 232

Answers (3)

Jonathan Badillo
Jonathan Badillo

Reputation: 1

Your code is not adding hours to the input date. What is happening is that your date string is using a particular timezone GMT-0700 (Mountain Standard Time) and the time zone used in new Date().toISOString() is UTC GMT+0000 (UTC). So when in the Mountain Standard Time timezone is Mon Feb 04 2019 15:57:02, in the UTC timezone is actually 2019-02-05T22:57:02.000Z. There are your seven hours from GMT-0700 to GMT+0000.

EDITED

If you don't really care about time zones and want to obtain 2019-02-04T15:57:02.000Z from Mon Feb 04 2019 15:57:02 GMT-0700 (Mountain Standard Time) you could just strip everything after GMT to let new Date() think it is an UTC date.

var timeString = 'Mon Feb 04 2019 15:57:02 GMT-0700 (Mountain Standard Time)';
new Date(timeString.substr(0, timeString.indexOf('GMT') + 3));

2019-02-04T15:57:02.000Z

Upvotes: 0

Zack
Zack

Reputation: 292

I'm not sure how to get this as a one-liner, but this is one way:

var time = new Date('Mon Feb 04 2019 15:57:02 GMT-0700 (Mountain Standard Time)')
new Date(time.setHours(time.getHours() + 7)).toISOString()

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

Upvotes: 0

Heretic Monkey
Heretic Monkey

Reputation: 12114

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.

Upvotes: 4

Related Questions