如何在Angular中设置格式/日期(1524210579389)

如何在Angular中设置格式/日期(1524210579389),angular,Angular,如何在HTML模板中格式化日期?它当前显示这个 /日期(1524210579389)默认情况下,角度传感器提供管道 例如: <div> <h2> {{binded_date | date: 'MMMM yyyy' }}</h2> </div> {{binded_date}date:'MMMM-yyyy'} 输出: 2018年4月 您可以在angular上找到更多类似的示例,而无需任何自定义管道 只需像这样从角度调用datepipe {{g

如何在HTML模板中格式化日期?它当前显示这个


/日期(1524210579389)

默认情况下,角度传感器提供管道

例如:

<div>
  <h2> {{binded_date | date: 'MMMM yyyy' }}</h2>
</div>

{{binded_date}date:'MMMM-yyyy'}
输出: 2018年4月

您可以在angular

上找到更多类似的示例,而无需任何自定义管道 只需像这样从角度调用
date
pipe

{{getDate("/Date(1524210579389)") | date}}

getDate(value) {
    return value.match(/\d+/)[0] * 1
  }

如果需要更改格式,您可以选择以下选项之一


您必须创建一个自定义管道,将
/date(xxxxxxxxxxxx)/
格式中的日期格式化为带时区的json日期对象。然后,您可以使用内置的
DatePipe
来获取所需的格式,而无需拆分日期

通常,在序列化json中的DateTime值时,.NET MVC json序列化程序会返回此类格式。这个问题在WEB API 2中不存在,因为当我们返回http响应时,WEB API使用JSON.NET序列化日期时间

自定义日期管道代码

自定义-date.pipes.ts

import { Pipe, PipeTransform } from '@angular/core';
/*
 * Formats a /Date(xxxxxxxxxxxxx)/ into a JSON Date object
 * Takes an argument as input of actual date value in /Date(xxxxxxxxxxxxx)/ format.
 * Usage:
 *   date-value | customDateFormat
 * Example:
 *   {{ '/Date(1402034400000)/' | customDateFormat}}
*/
@Pipe({name: 'customDateFormat'}  )
export class CustomDateFormat implements PipeTransform {
  transform(value: any): Date {
       var customDate = new Date(value.match(/\d+/)[0] * 1);  
       return  customDate;
  }
}
部件代码
app.component.ts

import { Component } from '@angular/core';
import {DatePipe} from '@angular/common'

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 5';
  originalDate:string = '/Date(1524210579389)/';
}
在HTML模板中的用法

app.component.html

<p>Original date: {{originalDate}}</p> <br>
<p>Custom date: {{originalDate | customDateFormat|date :'short'}}

工作演示:

请发布您的代码。使用DatePipe您使用的是Angular2还是angularjs?发布组件的代码。@ShaneKm请检查我对自定义管道的回答,您需要将json响应中的日期值以HTML形式传递给管道。我有这个/date(1524210579389),我没有唯一的数字。然后将其拆分并从中获取时间戳编号,顺便说一句,这不是任何类型的有效格式Date@PardeepJain这是来自.NET MVC json序列化程序的有效格式。@ShaneKm检查我的答案。@ShaneKm现在检查我的答案,我想说的是为了分割你的日期,即使没有任何额外的管道
Custom date: 4/20/18, 1:19 PM