简体   繁体   中英

AngularJS Date Format Issue

On trying the inbuilt angularjs date filter to format the date string, I am not getting the formatted date for "2016-05-17 14:45:59+04",

See the plunkr https://plnkr.co/edit/VzRpNFkrWasv3nPlIQyg?p=preview ,

Please help me in understanding why it is working and I am getting the proper date object when I parse the string "2016-05-17 14:45:59+04" using see the screenshot

在此处输入图片说明

Thanks in advance for any help.

 <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Example - example-example101-production</title> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script> </head> <body ng-app=""> <span ng-non-bindable>{{2016-05-17 14:45:59+04 | date:'yyyy-MM-dd'}}</span>: <span>{{'2016-05-17 14:45:59+04' | date:'yyyy-MM-dd'}}</span><br> </body> </html> <!-- Copyright 2016 Google Inc. All Rights Reserved. Use of this source code is governed by an MIT-style license that can be found in the LICENSE file at http://angular.io/license --> 

Use Javascript Date object instead of passing it as a string.

// somewhere in the controller

$scope.dt = new Date('2016-05-17 14:45:59+04');

// in html

<span>{{dt | date:'yyyy-MM-dd'}}</span>

You can also write custom filter to do it, which you have already done.

Key point here is using Javascript Date object

您应该使用符合ISO 8601的日期/时间格式:

<span>{{'2016-05-17T14:45:59+04:00' | date:'yyyy-MM-dd'}}</span><br>

Quote from the link that you provided , under Usage > Arguments:

Date to format either as Date object, milliseconds (string or number) or various ISO 8601 datetime string formats (eg yyyy-MM-ddTHH:mm:ss.sssZ and its shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is specified in the string input, the time is considered to be in the local timezone.

So, choose a different format for your date string, for example:

2016-05-17T14:45:59.000+0400

If you want to to avoid being forced to do new Date() in your controller each time you have to handle date, you can use a filter that will automatically transform your date into a new Date() :

angular
    .module('myApp')
    .filter('toNewDate', toNewDate);

function toNewDate() {
    return toNewDateFilter;

    ////////////////

    function toNewDateFilter(date) {
        return new Date(date);
    }

}

Now you can use it through your application and save lots of time (eg when you receive dates from webservices):

<span class="date">{{post.created_at| toNewDate | date: 'dd MMMM yyyy'}}</span>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM