1

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?

3 Answers 3

1

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

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

2 Comments

Thank you for the suggestion but it is not working. Can you please try below 2 dates: ctrl.date1 = new Date("2018-05-22T22:35:04.000Z"); ctrl.date2 = new Date("2018-05-22T10:35:04.000Z")
Yes, it wouldn't work when ctrl.date1 > ctrl.date2 because we're performing subtraction of date1 from date2
0

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;
}

Comments

0

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.

Comments

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.