Datepipe angular 2未显示正确的结果
下面是我的代码。使用angular 2内置日期管道将时间戳转换为正确的日期格式Datepipe angular 2未显示正确的结果,angular,date-pipe,Angular,Date Pipe,下面是我的代码。使用angular 2内置日期管道将时间戳转换为正确的日期格式 import { Component } from '@angular/core'; @Component({ selector: 'my-app', template:`<h1>My First Angular 2 App</h1> <p>{{test | date: 'dd/MM/yyyy'}} - format: dd/MM/yyyy</p>` }) expo
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template:`<h1>My First Angular 2 App</h1>
<p>{{test | date: 'dd/MM/yyyy'}} - format: dd/MM/yyyy</p>`
})
export class AppComponent {
test : Date = '2017-04-30T23:59:59';
}
从'@angular/core'导入{Component};
@组成部分({
选择器:“我的应用程序”,
模板:`我的第一个Angular 2应用程序
{{test | date:'dd/MM/yyyy'}}-格式:dd/MM/yyyy`
})
导出类AppComponent{
测试:日期='2017-04-30T23:59:59';
}
输出:
2017年5月1日-格式:年月日
但我预计2017年4月30日是我的输出,我的解决方案如下
//our root app component
import {Component, NgModule, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2><br>
<h5>{{test | date: 'dd/MM/yyyy'}}</h5>
</div>
`,
})
export class App {
name:string;
test : Date = new Date('2017-04-30T23:59:59');
constructor() {
this.name = `Angular! v${VERSION.full}`;
console.log(this.test)
}
}
使用上述方法获得确切的日期,因为Pankaj说日期管道不适用于您的案例。演示已更新我认为您遇到了时区问题 发件人: 设置日期时,不指定时区,JavaScript将 使用浏览器的时区 获取日期时,如果不指定时区,则结果为 转换为浏览器的时区 当我测试在JSFIDLE的构造函数中使用您的字符串创建一个日期并将其注销时,我得到的时间比我定义的时间晚了5个小时,这将对应于GMT 尝试使用指定的时区设置日期:
test : Date = new Date('2017-04-30T23:59:59Z');
如果只想显示日期,请使用此选项
<div>{{test.split("T")[0] | date : 'dd/MM/yyyy'}}</div>
{{test.split(“T”)[0]|日期:'dd/MM/yyyy'}
test:Date=new Date('2017-04-30T23:59:59')
使用它仍然会给出相同的输出Date
管道将在Date
值上工作,而不是在string
值上工作,您必须将字符串值转换为Date
,然后在其上应用Date
管道..刚刚运行了演示。它给了我2017年5月1日的输出。我预计2017年4月30日将作为输出,现在是哪个时区?
<div>{{test.split("T")[0] | date : 'dd/MM/yyyy'}}</div>