typescript 将 new Date() 转换为打字稿中的 UTC 格式,角度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/53697849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting new Date() to UTC format in typescript, angular
提问by RN92
I have a request from angular, which sends date to server.
我有一个来自 angular 的请求,它将日期发送到服务器。
const activationDate = new Date();
I need to convert this to UTC date format before sending the request
我需要在发送请求之前将其转换为 UTC 日期格式
In my model, I have a Date variable to pass the date to server
在我的模型中,我有一个 Date 变量来将日期传递给服务器
export class PersonDetails {
id: string;
activationDate?: Date;
}
采纳答案by RN92
personModel: PersonDetail;
const activationDate = new Date();
this.personModel.activationDate = new Date(activationDate.getUTCFullYear(),
activationDate.getUTCMonth(),
activationDate.getUTCDate(),
activationDate.getUTCHours(),
activationDate.getUTCMinutes(),
activationDate.getUTCSeconds()
);
OR Can use a separate method to get UTCDate
或 可以使用单独的方法来获取 UTCDate
const activationDate = this.getNowUTC();
private getNowUTC() {
const now = new Date();
return new Date(now.getTime() + (now.getTimezoneOffset() * 60000));
}
回答by Maarti
You can use toISOString()
function (MDN web docs).
您可以使用toISOString()
函数(MDN 网络文档)。
The timezone is always zero UTC offset.
时区始终为零 UTC 偏移量。
const activationDate = new Date().toISOString();
回答by Akshay Rajput
Although the above solutions are correct if you need to play with the date a lot you can use moment.js lib which might be really helpful.
虽然上述解决方案是正确的,如果您需要经常使用日期,您可以使用 moment.js lib,这可能非常有用。
Refer http://momentjs.com/docs/#/parsing/utc/for more.
有关更多信息,请参阅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());
回答by Pàldi Gerg?
I created a pipe like this
我创建了一个这样的管道
@Pipe({ name: 'UTCDate'})
export class UTCDatePipe implements PipeTransform {
constructor() {}
transform(value) {
if (value) {
return moment.utc(value).format('YYYY MMMM DD');
} else {
return '';
}
}
}
And view like this:
并像这样查看:
{{invoice.invoiceDate | UTCDate}}
and to this app.module
和这个 app.module
import {UTCDatePipe} from "@app/utcDate.component";
@NgModule({
declarations: [
AppComponent,
UTCDatePipe
],