Akash Gadhiya
Akash Gadhiya

Reputation: 380

Display day with hours in Angularjs

Here are date and time.

Date 2018-05-25T10:35:04.000Z

Expected Output = 3 days 12 hours

I want to display date and time same like as a give above. Currently, I am using moment.js. Is there any way to display like above?

Upvotes: 1

Views: 78

Answers (3)

Nate B.
Nate B.

Reputation: 942

You should consider using The HumanizeDuration library (you can check this answer). It allows you to translate in any language you want the difference between two dates the way you want.

For example :

var yourdate= moment().set({'year': 2018, 'month': 5, 'day': 22});
var today = moment();
var duration = moment.duration(today.diff(yourdate));
var humanized = humanizeDuration(duration, { units: ['d', 'h'], language: language, round: true });

You can also format it with spacers, etc.

Upvotes: 0

Protozoid
Protozoid

Reputation: 1207

Alternatively to Zvi's suggestion, you could use the AngularJS date filter

Say in your controller you have 2 dates:

app.controller('AppCtrl', function($scope) {
    ctrl = this;

    ctrl.date1 = new Date("2018-05-22T22:35:04.000Z");
    ctrl.date2 = new Date("2018-05-25T10:35:04.000Z");
});

And in HTML, you'd display the difference with the date filter:

{{ctrl.date2 - ctrl.date1 | date:"dd 'days' HH 'hours'"}}

Here's a working JSFiddle example

Upvotes: 1

Zvi
Zvi

Reputation: 617

You can use this moment-precise-range.

Here's full example:

calcDiff = (date : string) => {
    let diff_in_string = '';
    let original_date = moment(date);
    let date_time_now = moment();
    let diff_in_object: any = moment-presice.preciseDiffBetweenDates(original_date, date_time_now, true);
    if (diff_in_object.days > 0) {
        diff_in_string = diff_in_string + diff_in_object.days + ' ';
        if (diff_in_object.days === 1) {
            diff_in_string += 'Day '
        } else {
            diff_in_string += 'Days '
        }
    }
    if (diff_in_object.hours > 0) {
        if (diff_in_object.days > 0) {
            diff_in_string += 'and ' + diff_in_object.hours + ' '
        } else {
            diff_in_string += diff_in_object.hours + ' '
        }
        if (diff_in_object.hours === 1) {
            diff_in_string += 'Hour '
        } else {
            diff_in_string += 'Hours '
        }
    }
    diff_in_string += 'ago'
    return diff_in_string;
}

Upvotes: 0

Related Questions