james emanon
james emanon

Reputation: 11807

moment.js and deprecated warning. timestamp to moment date object

I've read thru various posts on here in regards to similiar issues but none have solved my problem.

I manipulate the moment.js date object, and then store it as timestamp.

BUT, when I try to read in that timestamp again, I get that deprecated warning.

""Deprecation warning: moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues/1407 for more info."

I've tried toDate(), format(), moment(myTimeStamp, 'ddd, DD MMM YYYY HH:mm:ss ZZ'); --> all generate the warning...

So, for example, my timestamp will look like this:

const timestamp = '1458586740000'

when I read that back and try to parse out the month/day/year, then the hour/min am/pm, etc... I need to get that timestamp into a moment.js object. Nothing is working for me. Any ideas.

How can I get this timestamp: '1458586740000', into a moment.js object so I can extract date date from it as I need?

EDIT: this is how I am storing the timestamp. So I would need to retrieve it from this.

let timeStamp = Moment(state[_Date])
                           .add({ hour: state[AMPM] === 'PM'
                                      ? +state[Hour] + 12
                                      : state[Hour] ,
                                  minute: state[Min] }).format('x')

Upvotes: 2

Views: 2349

Answers (1)

Maggie Pint
Maggie Pint

Reputation: 2452

The X token indicates a unix timestamp in seconds, and the x token indicates a unix millisecond timestamp (offset). You appear to have a millisecond timestamp, so you would make a moment out of it by doing the following:

var a = moment('1458586740000', 'x')

It works without ' as well:

var a = moment(1458586740000, 'x')

You can also not specify the x and it should work:

moment(1458586740000)

Because you have a unix offset (milliseconds), not a unix timestamp (seconds), moment.unix is not what you want.

Then you can do the following:

a.format()
"2016-03-21T13:59:00-05:00"

Or you can use any of the other formatting tokens listed here to output whatever result you would like: http://momentjs.com/docs/#/displaying/format/

Based on the code you presented, I think you may be having problems because your timestamp is stored as a string (in ''). Parsing as a string causes an invalid date error, because it attempts to match ISO 8601 format and fails. Specifying that 'x' token will cause it to assume unix offset and work correctly.

Upvotes: 6

Related Questions