将 new Date() 转换为打字稿中的 UTC 格式,angular

Converting new Date() to UTC format in typescript, angular

我有一个来自 angular 的请求,它向服务器发送日期。

const activationDate = new Date();

我需要在发送请求之前将其转换为 UTC 日期格式

在我的模型中,我有一个 Date 变量来将日期传递给服务器

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

const activationDate = new Date();

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

或 可以使用单独的方法获取 UTCDate

const activationDate = this.getNowUTC();    

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

A good article on converting DateTime

您可以使用 toISOString() 函数 (MDN web docs)。

The timezone is always zero UTC offset.

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

尽管上述解决方案是正确的,但如果您需要经常使用日期,您可以使用 moment.js 库,这可能真的很有帮助。

参考http://momentjs.com/docs/#/parsing/utc/了解更多。

1. npm install moment
2. import * as _moment from 'moment';
const moment = _moment;
const utcDate = moment.utc();
console.log(utcDate.format());

我创建了一个这样的管道

@Pipe({ name: 'UTCDate'})
export class UTCDatePipe implements PipeTransform  {
    constructor() {}
    transform(value) {
        if (value)  {
            return  moment.utc(value).format('YYYY MMMM DD');
        } else {
              return '';
        }
    }
}

并像这样查看:

{{invoice.invoiceDate | UTCDate}}

和这个 app.module

import {UTCDatePipe} from "@app/utcDate.component";

@NgModule({
    declarations: [
        AppComponent,
        UTCDatePipe
    ],