HurricaneDancer
HurricaneDancer

Reputation: 11

Creating a UTC date in typescript

I am currently trying to force my application to use UTC time no matter what the system time is. I have a method to create a date:

  public static createDate(date: Date = new Date()): Date {
    return new Date(
      Date.UTC(
        date.getUTCFullYear(),
        date.getUTCMonth(),
        date.getUTCDay(),
        date.getUTCHours(),
        date.getUTCMinutes(),
        date.getUTCSeconds(),
        date.getUTCMilliseconds()
      )
    );
  }

However, I get a time that is 8 hours ahead when it lands in the database. I am not sure what is going on here.

I have tried using other solutions on stack overflow, using libraries like moment and date-fns but i have not had any luck.

Upvotes: 1

Views: 7577

Answers (2)

HurricaneDancer
HurricaneDancer

Reputation: 11

I realized that because i had set the time on my computer manually, it was using a different time zone, so it was returning a different time. It seems to be fine now.

Upvotes: 0

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241420

The Date object is already in UTC. It always is, because the only value it stores internally is a UTC-based numeric timestamp representing the number of milliseconds since 1970-01-01 00:00:00.000 UTC. You can see that timestamp directly with either .getTime() or .valueOf() or by any mechanism that coerces the Date object to a Number. You can also see a string representation of it with .toISOString().

The approach you demonstrated in your question is simply a long and slow way to copy the Date object. You would get the same result with new Date(date).

You said you are having trouble with the time being offset in the database, but you've not shown that part of the code or described anything about your database, so I can't answer that directly. Likely you've got a subtle error in how you pass the Date object into the database that is converting to local time.

Upvotes: 1

Related Questions