0

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');
    } });
1
  • use custom filter Commented Apr 26, 2017 at 5:19

2 Answers 2

1

Use Moment.js while displaying like

{{moment(date).calendar()}} // Today at 11:17 AM

For reference: https://momentjs.com/

Sign up to request clarification or add additional context in comments.

1 Comment

Have to agree with Shanky, moment is your best bet.
0

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.

1 Comment

I need a directive which will automatically check for date and display related date format

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.