Thomas Charlesworth
Thomas Charlesworth

Reputation: 1839

moment utc start from day incorrect

I am trying to get moment to give me the minutes ago since that specific date. I send in date as a UTC time format. The first format to DD MMM YYYY, h:mm a is correct. However, the time ago is all 35 which is incorrect.

Sat Nov 11 2017 00:13:45 GMT+0700 (+07)
11 Nov 2017, 12:13 am
35 minutes ago
Sat Nov 11 2017 00:10:46 GMT+0700 (+07)
11 Nov 2017, 12:10 am 
35 minutes ago
Sat Nov 11 2017 00:12:08 GMT+0700 (+07)
11 Nov 2017, 12:10 am 
35 minutes ago
Sat Nov 11 2017 00:07:57 GMT+0700 (+07)
11 Nov 2017, 12:07 am
35 minutes ago

Code:

    console.log(date)
    console.log(moment(date).local().format('DD MMM YYYY, h:mm a'))
    if(today.diff(date, 'days') < 5){
        date = moment(date).local().startOf('day').fromNow()
        console.log(date)            
    }else{
        date = moment(date).local().format('DD MMM YYYY, h:mm a')
    }

Upvotes: 0

Views: 1189

Answers (1)

Robbie Milejczak
Robbie Milejczak

Reputation: 5770

Use diff instead, and then specify the units as minutes.

let date = '2017/02/22 08:42:22';
let diff = moment(date).diff(moment(date).startOf('day'), 'minutes');

You can also do

let date = '2017/02/22 08:42:22';
let diff = moment(date).diff(moment(date).startOf('day'));

Which returns the difference as milliseconds and then display it via

moment.duration(diff).asMinutes();
moment.duration(diff).asHours();

etc.

If you want to mix units you can do:

`${Math.floor(moment.duration(diff).asHours())}:${moment.duration(diff).minutes()}`

Documentation

edit: oops, forgot proper syntax. Thats what I get for writing this from memory

Upvotes: 1

Related Questions