2016-02-26 76 views
4

這似乎是一個簡單的問題。我在我的Ionic 2應用程序中使用管道進行日期格式化。這是接收到的web服務響應。管道'DatePipe'的參數'日期格式'無效?

[ 
    { 
    "MessageID": 544882, 
    "CategoryID": 1, 
    "DateSent": "2015-05-18T02:30:56", 
    "Title": "Jobseeker App", 
    "MessageContent": "Hi Test guy just started to use the app..", 
    "Sender": null, 
    "Recipient": null, 
    "DateReceived": null, 
    "DateRead": "2015-05-18T02:30:56", 
    "Note_Direction": "sent", 
    "Viewed": 0, 
    "AppointmentDateTime": null, 
    "MessageAttachments": [ 

    ] 
    }, 
    { 
    "MessageID": 544886, 
    "CategoryID": 1, 
    "DateSent": "2015-05-18T02:42:45", 
    "Title": "Jobseeker App", 
    "MessageContent": "App", 
    "Sender": null, 
    "Recipient": null, 
    "DateReceived": null, 
    "DateRead": "2015-05-18T02:42:45", 
    "Note_Direction": "sent", 
    "Viewed": 0, 
    "AppointmentDateTime": null, 
    "MessageAttachments": [ 

    ]} 
    ] 

這是我正在使用的代碼片段。

<div class="Date"> 
<label class="time">{{appointment.DateSent | date:"HH"}}:{{appointment.DateSent| date:"mm"}}</label> 
<label class="month">{{appointment.DateSent| date:"MMM"}}</label> 
<label class="day">{{appointment.DateSent| date:"dd"}}</label> 
<label class="year">{{appointment.DateSent| date:"yyyy"}}</label> 
</div> 

錯誤:

Invalid argument '2015-05-18T02:30:56' for pipe 'DatePipe' in [{{appointment.DateSent | date:"HH"}}:{{appointment.DateSent| date:"mm"}} in [email protected]:37] 

我需要得到一個日期格式是這樣的:

06:05 
Dec 
24 
2015 

回答

4

您傳遞錯誤的參數,所以角投擲的錯誤。改變你的日期代碼與此:

birthday = 2015-05-18T02:30:56 //Working 
birthday2 = new Date(2015-05-18T02:30:56) //Working 

Oldbirthday = '2015-05-18T02:30:56' //Not Working 

我在這裏使用可變birthday insted的您的變量名。 可能是錯誤的原因是角度可能不接受日期爲格式的字符串。根據me.But作爲官員

  • this pipe is marked as pure hence it will not be re-evaluated when the input is mutated. Instead users should treat the date as an immutable object and change the reference when the pipe needs to re-run (this is to avoid reformatting the date on every change detection run which would be an expensive operation). https://angular.io/docs/ts/latest/api/common/DatePipe-class.html

工作plnkr http://plnkr.co/edit/b9Z090rQpozMoMi0BWaY?p=preview

更新:

需要時由@Kanishka是你可以更新日期和HTML側變成new date()你必須調用typecript的setter和getter函數相同。這裏是你正在尋找的例子。所以通過使用這個我不認爲你需要從repsonse創建你自己的數組。我希望它可以幫助你,並建議你一個新的方法來玩前端的迴應。

<label>{{setDate('2015-05-18T02:30:56') | date:"yyyy"}}</label> 

    get Anotherdate(){ //getter function 
    return this.date 
    } 
    setDate(date) { 
    this.Anotherdate = date; 
    return this.Anotherdate; 
    } 
    set Anotherdate(date){  // Setter Function 
    this.abc = new Date(date) 
    } 

這裏更新工作演示http://plnkr.co/edit/rHCjevNcol12vwW6B38u?p=preview

+0

謝謝Pardeep,但作爲輸出我越來越05:30 1970年1月1日爲2015-05-18T02:30:56。我如何轉換'2015-05-18T02:30:56'至2015-05-18T02:30:56? – happycoder

+0

您必須使用新的Date()方法將其轉換並將所需的日期作爲參數傳遞。看看我的plnkr我已經更新了你說的代碼。 –

+1

'newDate = new Date('2015-05-18T02:30:56');'像這樣。 –