How to display date in different formats in ng-repeat - angularjs - angularjs

I have a date as "2017-04-03 05:00:07". I need to check for the date is today's date. If it is today's date i need to display as today or time.
If it is yesterday's need to display as yesterday or date as "MMM dd"
If it is last month or with in this year then, "MMM dd".
If it is last year then dd/mm/yyyy
I tried to display like this using a directive but this is not working for me.
Is there anyother way?
app.directive('myDirective', function($filter) {
return {
restrict: "A",
scope: {
myDirective: '='
},
link: function(scope, element, attrs) {
var date1 = new Date(scope.myDirective.updateddate);
var date2 = new Date();
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
if (diffDays == 1) {
scope.myDirective.updateddate = 'yesterday'
} else if (diffDays > 2 && diffDays <= 365) {
scope.myDirective.updateddate = $filter('date') scope.myDirective.updateddate, 'dd-MMM');
}
else if (diffDays > 365) {
scope.myDirective.updateddate = $filter('date') scope.myDirective.updateddate, 'dd-MM-YYYY');
} });

Use Moment.js while displaying like
{{moment(date).calendar()}} // Today at 11:17 AM
For reference: https://momentjs.com/

Using a custom filter is the most correct approach to this.
You define a filter much like a directive:
app.filter('myfilternamehere', function() {
return function(input) {
//do some stuff that creates the correct output
return output;
}
});
I have created a JSFiddle that might contain a solution for your problem and at the same time shows you how to create a custom directive in a bit more detail.

Related

Formating MYSQL datetime in Angular doesn't work in Safari browser

I want to format MYSQL datetime (eg. 2017-02-07 22:58:22), so I've found, that it's necessary to convert it to ISO format with this filter first:
angular.module('datePipe',[]).filter('dateToISO', function() {
return function(input) {
input = new Date(input).toISOString();
return input;
};
});
This works in chrome and also in firefox, but not in safari :( There it throws error:
Error: Invalid Date toISOString#[native code]
How can I fix this error? Thank you :)
I found the solution:
html
<div class="date-left">{{ newie.created_at | dateParser | date:'d. M. yyyy' }}</div>
and here's dateParser
angular.module('datePipe',[]).filter('dateParser', function() {
return function(input) {
var year = input.substr(0,4);
var month = input.substr(5,2);
var day = input.substr(8,2);
return year + "-" + month + "-" + day;
};
})
I just wanted to display date only :)

angular material date picker field value empty

I want to get date of birth of a user, with predefined min and max date which is working fine.
And the date format i want is DD-MM-YYYY, for this i have defined following in config;
app.config(['$mdDateLocaleProvider', function ($mdDateLocaleProvider) {
$mdDateLocaleProvider.formatDate = function(date) {
return moment(date).format('DD-MM-YYYY');
}}]);
and the controller has
$scope.user = {};
$scope.user.dob = new Date();
$scope.maxDate = new Date(
$scope.user.dob.getFullYear() - 10,
$scope.user.dob.getMonth(),
$scope.user.dob.getDate()
);
$scope.minDate = new Date(
$scope.user.dob.getFullYear() - 120,
$scope.user.dob.getMonth(),
$scope.user.dob.getDate()
);
and the HTML is;
<md-datepicker
ng-model="user.dob"
md-placeholder="Enter date of birth"
md-min-date="minDate"
md-max-date="maxDate">
</md-datepicker>
with this code the field shows current date by default, which i don't want,
i want the date field to be empty by default.
Also i want to get values in both ways as follows
1) date-month-year
And
2) date-month-year hour-minutes-seconds
When i tried to get the value it shows this "09-11-2016T18:30:00.000Z"
i want either "09-11-2016" or "09-11-2016 18:30:00"
Your mdDateLocaleProvider doesnt check for null values.
Your Problem is:
app.config(['$mdDateLocaleProvider', function ($mdDateLocaleProvider) {
$mdDateLocaleProvider.formatDate = function(date) {
return moment(date).format('DD-MM-YYYY');
}}]);
it needs to be something like:
$mdDateLocaleProvider.formatDate = function(date) {
var m = moment(date);
return m.isValid()? m.format('DD-MM-YYYY') : '';
};
Then you can set
$scope.user.dob=null;
And get an empty Datepicker.
The problem is your ng-model. You're initializing it with the current date:
$scope.user.dob = new Date();
Simply empty this variable and you'll be good ;)

Angular date range filter

I was wondering if anyone could help me. I'm currently trying to get a date filter to work in Angular. I could be going about this completely the wrong way but just thought I would ask.
I currently have an ng-repeat looping through an array of objects. My objects have the following fields: title, sentBy and recevied. Received is in UTC format and my filter basically takes two inputs also in utc format for start and end date. The filter then checked if the received is greater than or equal to to start date or less than or equal to the end date. My issue is that the input to the filter is the input of the whole object. Im not sure how to access the received field of the object within the filter to do the comparrison. I tried input.received but it didnt seem to work. heres a sample of my code.
.filter('dateRange', function(){
return function(input, startDate, endDate) {
if(input.received >= startDate && input <= endDate){
return input;
}
};
})
As I say I could be going about this completely wrong but any help would be greatly appreciated.
edit:
my html code is as simple as below:
<div ng-repeat="message in messages | dateRange: startDate : endDate " >
Try below code. You need to compare the time.
.filter('dateRange', function(){
return function(input, startDate, endDate) {
angular.forEach(input, function(obj){
if(obj.received.getTime() >= startDate.getTime() && obj.received.getTime() <= endDate.getTime()) {
return obj;
}
});
};
});
<div ng-bind="messages | dateRange: startDate : endDate " ></div>
or
<div> {{messages | dateRange: startDate : endDate }}</div>
In your code the filter is working on messages array, that means the first argument (input) is the array, and the return type has to be an array too. Have a look here.
Your code should be something like that:
<div ng-repeat="message in messages | dateRange: startDate : endDate" >
Your filter is:
.filter('dateRange', function() {
return function(input, startDate, endDate) {
var retArray = [];
angular.forEach(input, function(obj){
var receivedDate = obj.received;
if(receivedDate >= startDate && receivedDate <= endDate) {
retArray.push(obj);
}
});
return retArray;
};
});
Here is a plunker.

Convert birthday to age in angularjs

I want to display age of all my users to grid. I am reading data from facebook.I am not storing it at anywhere.
i am displaying date like :
{{ friend.birthday }}
How can i display age instead of displaying birthday.
if it is possible to create filters than how to create filter and how to apply it.
You can implement a function:
Controller:
$scope.calculateAge = function calculateAge(birthday) { // birthday is a date
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
HTML
{{ calculateAge(friend.birthday) }}
Or a filter:
app.filter('ageFilter', function() {
function calculateAge(birthday) { // birthday is a date
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
return function(birthdate) {
return calculateAge(birthdate);
};
});
HTML
{{ friend.birthday | ageFilter }}
Age algorithm taken from this SO answer.
[EDIT] If the age is less than 1 year, and you want to show months, you can modify the ageFilter to calculate the month difference:
app.filter('ageFilter', function() {
function calculateAge(birthday) { // birthday is a date
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
function monthDiff(d1, d2) {
if (d1 < d2){
var months = d2.getMonth() - d1.getMonth();
return months <= 0 ? 0 : months;
}
return 0;
}
return function(birthdate) {
var age = calculateAge(birthdate);
if (age == 0)
return monthDiff(birthdate, new Date()) + ' months';
return age;
};
});
Demo Plunker - Age Function
Demo Plunker - Age Filter
Demo Plunker - Age Filter with Months < 1 year
If you're value is just for example "05/01/2016". This will be a useful code to convert the date to birthday.
AngularJS
app.filter('ageFilter', function(){
return function(birthday){
var birthday = new Date(birthday);
var today = new Date();
var age = ((today - birthday) / (31557600000));
var age = Math.floor( age );
return age;
}
});
HTML
{{ relationTypePreDefined.birthdate | ageFilter }}
By the way I used this solution to convert a date coming from a jquery datepicker input to age.
If you are using momentjs. Then you can create filter simply by using this snippet
var now = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";
moment.utc(moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss")
Idk why I can never reply to people, says I need more rep but to rep I need to comment.. whatever.
In response to #Dean Christian Armada's, I kept getting an error regarding the filter. But changing to the following seems to work fine so I do appreciate it!
$scope.getAge = function(birthday){
var birthday = new Date(birthday);
var today = new Date();
var age = ((today - birthday) / (31557600000));
var age = Math.floor( age );
return age;
}
And for the HMTL
{{ getAge(birthdate) }}

Date Picker not populating after override Expand method in Extjs

I wanted to set different date in Extjs date picker by replacing default date of date picker that comes system date.
for that I override Date field - below is my code -
Ext.override(Ext.form.field.Date, {
expand: function() {
var value = this.getValue();
var customDate = '07/08/2013';
var myDate = new Date(customDate );
this.getPicker().setValue(Ext.isDate(value) ? value : myDate);
}
});
Now I was expecting myDate as default in picker.
But picker is not populating when I click on picker to select date.
Thanks
I fixed the issue myself. Here is the code to do that. Hopefully it will help someone and will save precious time.
Ext.override(Ext.form.field.Date, {
expand: function() {
var myDate = new Date('07/08/2017');
var value = this.getValue();
this.getPicker().setValue(Ext.isDate(value) ? value : myDate);
var me = this, bodyEl, picker, collapseIf;
if (me.rendered && !me.isExpanded && !me.isDestroyed) {
bodyEl = me.bodyEl;
picker = me.getPicker();
collapseIf = me.collapseIf;
me.isExpanded = true;
me.alignPicker();
bodyEl.addCls(me.openCls);
me.mon(Ext.getDoc(), {
mousewheel: collapseIf,
mousedown: collapseIf,
scope: me
}); Ext.EventManager.onWindowResize(me.alignPicker, me);
me.fireEvent('expand', me);
}
}
});

Resources