0

I have a date and a time stored in different strings in Typescript and I want to convert that into a Date.

It's driving me nuts because I'm in GMT-3 and the date is not what it should even though I'm using UTC.

I have 2 concerns: 1st, the date is not correct, and 2nd, is there a more "elegant" way to do this?

   parseDate(date: string, time: string) : Date {
        let d = new Date(Date.UTC(
          Number(date.substring(0,4)), 
          Number(date.substring(5,7)) - 1, 
          Number(date.substring(8)),
          Number(time.substring(0, 2)),
          Number(time.substring(3))
        ));
        return d;
      }

I'm testing with date '2018-02-09' and time '10:15' and I get Thu Feb 09 2018 07:15:00 GMT-0300 (SA Eastern Standard Time)

2 Answers 2

2

When using Date.UTC you are setting the Timezone to UTC, to use the browser timezone, you can simply use:

parseDate(date: string, time: string) : Date {
  return new Date(date + ' ' + time)
}
parseDate('2018-02-09', '10:15') // Fri Feb 09 2018 10:15:00 GMT+0100 (CET) - I'm in GMT+01
Sign up to request clarification or add additional context in comments.

Comments

1

That date actually looks fine, are you using toString() to see what it contains? That would always use your local timezone.

Try with toUTCString()

if you require nice parsing capabilities without importing a completely bloated library, I would advise fecha (https://github.com/taylorhakes/fecha)

2 Comments

sorry, I misstyped the date, it's corrected now; anyway, it does not look fine, the time is 07:15 and it should be 10:15; if I don´t use UTC then the date is 08 when it should be 09. I check the date using the console, because I want to use it as a Date and not as a String
Try console.log(date.toUTCString()) ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.