Konvertera new Date() till UTC-format i TypeScript, Angular


Jag har en förfrågan från Angular, som skickar datum till servern.

const activationDate = new Date();

Jag behöver konvertera detta till UTC-datumformat innan jag skickar förfrågan

I min modell har jag en Date-variabel för att skicka datumet till servern

export class PersonDetails {
  id: string;
  activationDate?: Date;
}

Svar #1

personModel: PersonDetail;    

const activationDate = new Date();

this.personModel.activationDate = new Date(activationDate.getUTCFullYear(),
                                            activationDate.getUTCMonth(),
                                            activationDate.getUTCDate(),
                                            activationDate.getUTCHours(),
                                            activationDate.getUTCMinutes(),
                                            activationDate.getUTCSeconds()
                                            );

ELLER Kan använda en separat metod för att få UTCDate

const activationDate = this.getNowUTC();    

private getNowUTC() {
  const now = new Date();
  return new Date(now.getTime() + (now.getTimezoneOffset() * 60000));
}

En bra artikel om att konvertera DateTime

Svar #2

Du kan använda toISOString()-funktionen (MDN webbdokument).

Tidszonen är alltid noll UTC-förskjutning.

const activationDate = new Date().toISOString();

Relaterade artiklar