How to get the date right using momentjs

Asked

Viewed 18,294 times

1

Personal talk.

I’m having some trouble trying to use the momentjs library to work with dates.

My problem is described below.

****--------- Datetime ----------****

Timestamp recebido do banco de dados -> 2016-07-12 17:21:40 <- ESTA É A DATA 'UTC' QUE ESTA RETORNANDO DO BANCO COMO STRING

moment.tz(datetime, moment.tz.guess()); //datetime value is '2016-07-12 17:21:40' and moment.tz.guess() is returning "America/Sao_Paulo"

// inspect the moment object returned
q{ _isAMomentObject:true, _i:"2016-07-12 17:21:40", _f:"YYYY-MM-DD HH:mm:ss", _isUTC:true, _pf:Object…} 
_a: Array[7]
_d:Tue Jul 12 2016 14:21:40GMT-0300 (BRT) <- ESTA É A DATA CORRETA QUE EU QUERO
_f:"YYYY-MM-DD HH:mm:ss"
_i:"2016-07-12 17:21:40"
_isAMomentObject:true
_isUTC:true
_isValid:true
_locale:B
_offset:-180
_pf:Object
_z:h
__proto__:Object

// moment object formatted .format('YYYY-MM-DD HH:mm:ss')
2016-07-12 17:21:40 <- ESSA É A DATA QUE ESTA RETORNANDO, E ESTA ERRADA

****-------------------****

Can anyone tell me why?

2 answers

3


You need to create the Moment object with a non-local UTC date. See:

var dataUtc = moment.utc("2016-07-12 17:21:40");
moment.tz(dataUtc, moment.tz.guess()).format('YYYY-MM-DD HH:mm:ss');

In your case, it would look something like this:

moment.tz(moment.utc(datetime), moment.tz.guess());

1

Try like this beast:

moment(new Date(dataretornadadobanco)).format('padrao')

Lista de padrões: 
moment.locale('pt-br');         // :|
moment().format('LT');   // 11:39 AM
moment().format('LTS');  // 11:39:41 AM
moment().format('L');    // 07/13/2016
moment().format('l');    // 7/13/2016
moment().format('LL');   // July 13, 2016
moment().format('ll');   // Jul 13, 2016
moment().format('LLL');  // July 13, 2016 11:39 AM
moment().format('lll');  // Jul 13, 2016 11:39 AM
moment().format('LLLL'); // Wednesday, July 13, 2016 11:39 AM
moment().format('llll');  // Wed, Jul 13, 2016 11:40 AM

If you want to take only the date take the format and take the _d...

  • It is not good practice to take the value of the variable directly _d because this is an internal library usage variable. Alias I believe it is a bug they are exposed like this. It should have inside a closure.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.