Reputation: 7703
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
-->
Upvotes: 1
Views: 980
Reputation: 11
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 (e.g. when you receive dates from webservices):
<span class="date">{{post.created_at| toNewDate | date: 'dd MMMM yyyy'}}</span>
Upvotes: 0
Reputation: 1585
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
Upvotes: 3
Reputation: 4385
You should use the ISO 8601 compliant date/time format:
<span>{{'2016-05-17T14:45:59+04:00' | date:'yyyy-MM-dd'}}</span><br>
Upvotes: 2
Reputation: 17035
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 (e.g. 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
Upvotes: 1