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?

Aleksey Solovey
  • 4,153
  • 3
  • 15
  • 34
Akash Gadhiya
  • 380
  • 1
  • 15

3 Answers3

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

Protozoid
  • 1,207
  • 1
  • 8
  • 16
  • 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") – Akash Gadhiya Jun 11 '18 at 13:03
  • Yes, it wouldn't work when ctrl.date1 > ctrl.date2 because we're performing subtraction of date1 from date2 – Protozoid Jun 11 '18 at 13:15
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;
}
Zvi
  • 577
  • 6
  • 19
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.

Nate B.
  • 942
  • 11
  • 31