Angular 将新日期()转换为typescript中的UTC格式,角度
我收到angular的请求,它将日期发送到服务器Angular 将新日期()转换为typescript中的UTC格式,角度,angular,typescript,datetime-format,utc,Angular,Typescript,Datetime Format,Utc,我收到angular的请求,它将日期发送到服务器 const activationDate = new Date(); 在发送请求之前,我需要将其转换为UTC日期格式 在我的模型中,我有一个日期变量将日期传递给服务器 export class PersonDetails { id: string; activationDate?: Date; } 或 可以使用单独的方法获得UTCDate const activationDate = this.getNowUTC(); pr
const activationDate = new Date();
在发送请求之前,我需要将其转换为UTC日期格式
在我的模型中,我有一个日期变量将日期传递给服务器
export class PersonDetails {
id: string;
activationDate?: Date;
}
或
可以使用单独的方法获得UTCDate
const activationDate = this.getNowUTC();
private getNowUTC() {
const now = new Date();
return new Date(now.getTime() + (now.getTimezoneOffset() * 60000));
}
您可以使用
toISOString()
函数()
时区始终为零UTC偏移
尽管上述解决方案是正确的,但如果您需要经常使用日期,您可以使用moment.js lib,这可能非常有用 有关更多信息,请参阅
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
],
“时刻”已被弃用。此答案已在两年前发布
{{invoice.invoiceDate | UTCDate}}
import {UTCDatePipe} from "@app/utcDate.component";
@NgModule({
declarations: [
AppComponent,
UTCDatePipe
],