angular - 覆盖 Date.prototype.toJSON 以解决 Angular 7 中的 TimeZone 问题
问题描述
我有一个 Angular 7 应用程序。我正在向我的服务器发送日期。但是由于时区,我的时间要提前 3 小时返回服务器。我了解到解决这个问题的唯一方法就是写作 Date.prototype.toJSON
。但是,我不知道角度,我应该在哪里写下面的代码以及如何写?(例如 index.html、app.module.ts、...)我在下面写了我的 stackblitz 示例。
Date.prototype.toJSON = function(key){
//This code return me as string like "25.02.0219 19:48:52"
return this.toLocaleDateString() + ' ' + this.toLocaleTimeString();
}
解决方案
您可以在您的应用程序的主入口点覆盖 Date 原型,在您的情况下是 AppModule.ts,因此它将可用于整个应用程序。
应用模块.ts
export class AppModule {
constructor() {
this.overrideDate();
}
overrideDate() {
Date.prototype.toJSON = function (key) {
//This code return me as string like "25.02.0219 19:48:52"
return this.toLocaleDateString() + ' ' + this.toLocaleTimeString();
}
}
现在您可以在您的组件中使用它。
save() {
console.log(this.myForm.value);
this.http.post("localhost:5000",this.myForm.value).subscribe(result => {});
}
希望这会有所帮助!
推荐阅读
- windows - 如何使用Ansible列出windows服务器c盘下的文件夹和文件
- oracle - 如何在 Oracle apex 5.0 中修复交互式网格的标题
- proxy - 如何为 HTTPS 使用正向代理?
- python - 语法适用于 MySQL,但不适用于 MYSQL DB Connector (Python)
- flutter - Flutter DropdownButtonFormField setState 在 onChanged 方法之外不起作用
- regex - Perl中替换正则表达式的意外结果
- java - 使用 Spring Boot 使用 JSON 数据
- python - 如何构建一个 yaml 文件来运行我的 python 代码
- microservices - 微服务应该可重用吗?
- angular - RxJs / Angular:通过地图循环内的订阅获取其他数据