Time Difference in Angular 6

Viewed 5535

I need to show time difference on UI updated every second.

What I tried is:

component.ts

import { Component, OnInit } from '@angular/core';
import 'rxjs/add/observable/of';
import 'rxjs/add/observable/interval';
import 'rxjs/add/operator/map';
import { Observable, Subscription } from 'rxjs/Rx';
import { DateUtil } from '../../../framework/Utils/DateUtil';

@Component({
  selector: 'app-time-difference',
  templateUrl: './time-difference.component.html',
  styleUrls: ['./time-difference.component.scss']
})
export class TimeDifferenceComponent implements OnInit {
  orderTime = '14-09-2018 14:00:00';
  today = new Date();

  clock: Observable<any>;
  timeDifference: string;

  constructor() { }

  ngOnInit() {
    this.clock = Observable
      .interval(1000)
      .map(() => {
        const orderDate = DateUtil.getDatefromString(this.orderTime, 'DD-MM-YYYY HH:mm:ss');
        const timeDifference = DateUtil.getDateDiffInHours(orderDate, new Date());
        return timeDifference;
      });

    this.clock.subscribe(
      res => console.log(res)
      );
  }
}

.html

<div class="row mt-5 ml-5" style="margin-left:20px;">
    {{clock | async}}
</div>

DateUtil func

static getDateDiffInHours(startDate, endDate)
{
    let start = moment(startDate);
    let end = moment(endDate);
    let diff = moment.duration(end.diff(start));
    let milliSec = diff.milliseconds();
    let dateString = moment(milliSec).format('DD-MM-YYYY HH:mm:ss');
    return moment(dateString, 'DD-MM-YYYY HH:mm:ss').toDate();
}

Can someone tell me where I made a mistake?

As I am not getting update time difference in UI but I am getting update duration object in Console

Static result on UI

PT10H13M26.992S

1 Answers

Well, it's not that the view doesn't get updated. If you look closely at what output you get in the console - it's always the same date. The implementation of getting time difference is quite messy and can be done in a better way.

Without any external util functions the implementation can look like following:

import { Component, OnInit } from '@angular/core';
import {Observable} from 'rxjs/Rx';
import {DateUtil} from '../utils/DateUtil';
import * as moment from 'moment';

@Component({
  selector: 'app-time-difference',
  templateUrl: './time-difference.component.html',
  styleUrls: ['./time-difference.component.css']
})
export class TimeDifferenceComponent implements OnInit {
  orderTime = '14-09-2018 14:00:00';
  clock: Observable<any>;

  constructor() { }

  ngOnInit() {
    // order date in millis (can be computed once)
    const orderDate: number = moment(this.orderTime, 'DD-MM-YYYY HH:mm:ss').valueOf();
    this.clock = Observable
      .interval(1000)
      .map(() => {
        return Date.now() - orderDate;
      });

    this.clock.subscribe(
      res => console.log(res) // Output difference in millis
    );
  }
}

And in the template you could utilise the Angular Date pipe the following way:

<div class="row mt-5 ml-5" style="margin-left:20px;">
    {{(clock | async) | date:'dd HH:mm:ss'}}
</div>

In case you want some special date format in the output you could map the clock observable in any way you like. For example:

const orderDate: number = moment(this.orderTime, 'DD-MM-YYYY HH:mm:ss').valueOf();
    this.clock$ = Observable
      .interval(1000)
      .map(() => {
        return Date.now() - orderDate;
      })
      .map((millis: number) => {
        return moment.duration(millis);
      })
      .publishReplay(1).refCount(); // so that calculation is performed once no matter how many subscribers

this.days$ = this.clock$.map(date => date.days());
this.hours$ = this.clock$.map(date => date.hours());
this.minutes$ = this.clock$.map(date => date.minutes());
this.seconds$ = this.clock$.map(date => date.seconds());

And in the template:

<ul>
    <li><span id="days">{{days$ | async}}</span>Days</li>
    <li><span id="hours">{{hours$ | async}}</span>Hours</li>
    <li><span id="minutes">{{minutes$ | async}}</span>Minutes</li>
    <li><span id="seconds">{{seconds$ | async}}</span>Seconds</li>
</ul>

Hope this helps.

Related