I have a json file with a released field that comes back with such format:
released: "2002-01-28"
I intend to display them sorted by date (earlier first) and only showing the year. I've used the truncate module (in my example, release: 4) and so far its showing only the first 4 characters, but I haven't succeed using orderby to sort it correctly.
Any pointers?
Also, in some items the released field comes back empty, any quick way to display just a "unknown" instead of a blank space?
Thanks!
<li ng-show="versions" ng-repeat="version in versions | filter: '!file' | orderBy: version.released">
{{version.released | release:4}} - {{version.format}} - {{version.label}}
</li>
Here is a date formatting filter I use. It takes a date and converts it into whatever format you wish, in your case, 'yyyy'. Bind the raw date stamp in your template and then 'orderBy' should work fine. This is how I always do it. Oh, you might not want the replace() function... that was specific to my last project.
.filter('DateFormat', function($filter){
return function(text){
if(text !== undefined){
var tempdate = new Date(text.replace(/-/g,"/"));
return $filter('date')(tempdate, "MMM. dd, yyyy");
}
}
})
You can show unknown by doing {{version.released || 'unknown'}}.
If you only want to show the year do this {{ (version.released | date : date : 'YYYY' ) || 'unknown'}}
Related
I have a table of names starting with a title (Mr, Mrs, etc) and dates stored as strings plus some other data.
I am currently sorting it using
<tr dir-paginate="booking in bookingResults | orderBy:sortType:sortReverse | filter:searchPassenger | itemsPerPage: 15">
How could I refine my orderBy to sort names excluding the title (Mr, Mrs, etc) and dates as parsed dates not strings.
What would be best practice here?
EDIT :
I don't want to change the names in the model by the way - I want the format to remain "Mr Foo" and "Mr Bar" but when I sort them I want them to act as if they were just "Foo" and "Bar".
EDIT EDIT :
AngularJS 1.5.6
getting the right data in the right format
title & name
I'd use a regexp to pull the title from the name:
var regex = /((Dr\.|Mr\.|Ms\.|Miss|Mrs\.)\s*)/gmi
objName.replace(regex, '')
date
I'm assuming you're getting either a date object or a standard date string. If it's the latter, just create a Date object via new Date(incomingDateString). Then you can call:
objDate.getTime() //returns epoch in milliseconds
sorting
Some people might dislike this but I hate dirtying up view controllers with methods that NG directives need to use for things like ordering. Instead, I added some ng-flagged properties using ng-init on each row item. Then I can sort based off that. I didn't do it for the date in the example but you could extrapolate and apply.
ng-init w. ng-flagged properties
<tr ng-repeat="row in vc.listData | orderBy:vc.sortKey track by $index"
ng-init="row.$name = row.name.replace(vc.regexp, '')">
So in other words your objects go from this:
{
name:'Mr. Fred Rogers',
date:<date-object>
}
to this thanks to ng-init:
{
name:'Mr. Fred Rogers',
date:<date-object>,
$name:'Fred Rogers',
$date:1466192224091
}
And then via your sorting UI, you can set your $scope.sortKey to either $name or $date.
code pen
I made a sample in code pen but I did it with my template which is coffeescript and jade. You can probably figure out what I'm doing.
pen - http://codepen.io/jusopi/pen/aZZjgG?editors=1010
Ok, after some research, I found that the easiest solution is upgrading to AngularJS version 1.5.7 which introduces the comparator into the orderBy filter.
So I've changed my repeater to use an order by comparator
<tr dir-paginate="booking in Results | orderBy:Variable:TrueOrFalse:bookingComparator">
Variable is a string which I bound to the table headings so you can change the order by key, TrueOrFalse is a boolean which alternates between ascending and descending if you click the table heading and bookingComparator is my actual comparator.
My booking comparator looks like this
$scope.bookingComparator = function (a, b) {
var getTitle = /((Mrs|Mr|Mstr|Miss|Dr)\s*)/g;
var isDate = /(-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-)/g
if (getTitle.test(a.value)) {
var aName = a.value, bName = b.value;
return aName.replace(getTitle, '') < bName.replace(getTitle, '') ? -1 : 1
}
if (isDate.test(a.value)) {
var aDate = new Date(a.value), bDate = new Date(b.value);
return aDate.getTime() < bDate.getTime() ? -1 : 1
}
return a.index < b.index ? -1 : 1
}
The comparator is basically a function acting like the javascript .sort() method.
If the value contains a title (Mr, Mrs, etc) it is a name so I strip the titles and compare the actual names regardless of title.
If the variable matches a -Month- pattern, it's a date string and I compare the parsed date objects.
Hope this is helpful to someone, took me a while to figure out. I'm open to suggestions if you think there's a better way of doing this, and feel free to post an answer for people who want to use AngularJS =< 1.5.6
I have a
As a scope I have: $scope.getDatetime = new Date();
And I wanna make the following work:
<span ng-show="getDatetime > foobar.datetime">Foobar</span>
The foobar.datetime is from ng-repeat with the format of: 2014-08-20 01:45:15
So I only wanna show that element, when current time is bigger then the datetime given.
Thought it was a easy as my example above, but it isn't - and I can't figure out if it's even possible without using plugins.
If I'm reading this correctly, then your issue is that your comparing a string and a date object. Try:
<span ng-show="getDatetime > getDate(foobar.datetime)">Foobar</span>
And in your javascript:
$scope.getDate = function(date) {
return new Date(date);
}
You need to convert your date to a timestamp, then you can compare the 2 dates, perhaps try using a filter to convert to a time stamp.
I was wondering if anyone could help me with filter on dates within ng-repeat
I have a text field that I enter the search text into for filter the results in my table
take this cut down example`
<tr id="credentialsData" ng-repeat="credential in credentials.data | filter:credentialsSearchText">
<td>{{credential.createdDate | date:'medium'}}</td>
</tr>`
credential.createdDate comes back in the rest call in the format 2015-03-24T21:19:49Z
When I attach the medium date filter - it displays as Mar 24, 2015 9:19:49 PM
However when i search on the String Mar or 9:, I get no results. Angularjs searches on the base object and ignores the filter.
I have read other options online where the person recommends adding different date formats into the json object but unfortunately that is not an option for me
Any help on this would be appreciated
Cheers
Damien
You can use a custom function for the filter.
https://docs.angularjs.org/api/ng/filter/filter
<tr id="credentialsData" ng-repeat="credential in credentials.data | filter:credentialsSearchText:compareCredentialDate">
<td>{{credential.createdDate | date:'medium'}}</td>
</tr>
In your controller, put a
$scope.compareCredentialDate = function(credential, expected) {
// you have to inject '$filter' to use this:
var dateFilter = $filter('date');
// this is the value that "credential.createdDate | date:'medium'"
// evaluates to:
var formattedDateString = dateFilter(credential.createdDate, 'medium');
// hypothetical matching method - you can implement whatever you
// want here:
var isMatch = formattedDateString.indexOf(expected) >= 0;
return isMatch;
}
As a response from the json I am getting the UTC timezone. I need to convert it to local time.
<span class="text-muted">{{trans.txnDate}}</span>
Can anyone help on this?
I just had to solve this problem as well with dates coming from .NET Web API in the format 'yyyy-MM-ddTHH:mm:ss' (e.g. 2016-02-23T00:11:31) without the 'Z' suffix to indicate UTC time.
I created this filter that extends the angular date filter and ensures that the timezone suffix is included for UTC time.
UTC to Local Filter:
(function () {
'use strict';
angular
.module('app')
.filter('utcToLocal', utcToLocal);
function utcToLocal($filter) {
return function (utcDateString, format) {
if (!utcDateString) {
return;
}
// append 'Z' to the date string to indicate UTC time if the timezone isn't already specified
if (utcDateString.indexOf('Z') === -1 && utcDateString.indexOf('+') === -1) {
utcDateString += 'Z';
}
return $filter('date')(utcDateString, format);
};
}
})();
Example Usage:
{{product.CreatedDate | utcToLocal:"dd.MM.yyyy"}}
EDIT (2nd Jan 2017): Please refer #Jason's answer, it is better than this one since it uses custom filter to fix the date format - that's the more Angular way of doing it.
My original answer and edits:
You could use the date filter to format the date:
<span class="text-muted">{{trans.txnDate | date:'yyyy-MM-dd HH:mm:ss Z' }}</span>
This will output:
2010-10-29 09:10:23 +0530
(assuming trans.txnDate = 1288323623006;)
See this documentation of date in angularjs.org. It has quite a few examples that are very helpful!
EDIT:
In response to your comment, use the following to get the date as 17 oct 2014:
<span class="text-muted">{{trans.txnDate | date:'dd MMM yyyy' | lowercase }}</span>
Check the documentation link that I mentioned above.
EDIT2:
In response to your other comment, use the following code. The problem is that the string that you are getting is not properly formatted so the Date object is not able to recognise it. I have formatted it in the controller and then passed to the view.
function MyCtrl($scope) {
var dateString = "2014:10:17T18:30:00Z";
dateString = dateString.replace(/:/, '-'); // replaces first ":" character
dateString = dateString.replace(/:/, '-'); // replaces second ":" character
$scope.date = new Date(dateString);
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="MyCtrl">
{{date | date:'dd MMM yyyy' | lowercase }}
</div>
The JS code for replacement can be improved by finding a smarter way to replace the first 2 occurrences of : character.
I had the same issue. AngularJs's date filter doesn't figure out the string is UTC format, but JavaScript Date object does. So I created a simple function in the Controller:
$scope.dateOf = function(utcDateStr) {
return new Date(utcDateStr);
}
And then used something like:
{{ dateOf(trans.txnDate) | date: 'yyyy-MM-dd HH:mm:ss Z' }}
It displays the date/time in the local timezone
I had the same issue. Below Answer
{{trans.txnDate | date:'yyyy-MM-dd HH:mm:ss Z':'+0530' }}
//You can also set '+0000' or another UTX timezome
Actual Date coming from JSON
Need to format it as below .
Effective Date : 2010-08-31 (trim the time stamp)
End Date : 2010-08-31 (trim the time stamp)
Am using the below code for Formatting the date inside Ng-Repeat.
<li ng-repeat="product in data | startFrom:currentPage*pageSize | limitTo:pageSize"
ng-click="getAttributes(product)">
{{product.prod_start_date| date:'MM/dd/yyyy'}}
{{product.prod_end_date| date:'MM/dd/yyyy'}}
</li>
But it doesnt work still displays the same.
Should the Date be passed as new Date as shown in the below jsfiddle Example
http://jsfiddle.net/southerd/xG2t8/
Note sure how to do that inside ng-repeat.?? Kindly help me on this. Thanks in Advance
I created my own filter to address this.
The date filter cant take a string, needs a date object.
.filter('cmdate', [
'$filter', function($filter) {
return function(input, format) {
return $filter('date')(new Date(input), format);
};
}
]);
then you can do:
{{product.prod_start_date| cmdate:'MM/dd/yyyy'}}
I use moment.js for my UI date time handling (there even a nice angular-moment bower package as well)
http://momentjs.com
https://github.com/urish/angular-moment
usage:
<span>{{product.prod_start_date | amDateFormat:'MM/dd/yyyy'}}</span>
It has a bunch of other options as well with relative dates etc.
I have updated the controller that you showed in the fiddle and here is your updated filter
Here I made use of the $filter('date') which is a feature of Angular itself in order to format the date in the desired format.
Here is the controller:
function Scoper($scope,$filter) {
$scope.s = "2012-10-16T17:57:28.556094Z";
var dateObj = new Date($scope.s);
$scope.dateToShow = $filter('date')(dateObj,'yyyy-MM-dd');
console.log($scope.dateToShow);
}