How to get the correct date using momentjs

1

Personal speech.

I'm having some problem trying to use the library momentjs 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 this is so?

    
asked by anonymous 13.07.2016 / 16:28

2 answers

2

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());
    
13.07.2016 / 16:50
1

So try 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 the date only take the format and get the _d ...

    
13.07.2016 / 16:40