Search code examples
javascriptangulartypescriptangular7angular8

Get difference between dates and format with 'DD/MM/YYYY HH:MM:SS'


How do I transform the milliseconds from date.now() into the format DD/MM/YYYY HH:MM:SS or transform a string with a date into milliseconds.

I also have a string which returns the following:

appointment: "21/11/2019 18:00:30"

I need to get the difference in hours between the date.now and appointment date


Solution

  • To transform a date, you can use DatePipe:

    let datePipe = new DatePipe();
    datePipe.transform(date, 'dd/MM/yyyy hh:mm:ss');
    

    To get the difference between Date.now() and a date, you can take a look at this answer, or you can use moment like that:

    import * as moment from 'moment';
    
    // ...
    
    const difference = moment(moment(),"DD/MM/YYYY HH:mm:ss").diff(moment(appointment,"DD/MM/YYYY HH:mm:ss"))
    

    You will need to install moment like that:

    npm install --save moment