12

Our postgres database returns a string with a timestamp: '2016-07-24T03:32:45.678Z'

We are trying to use the moment.js library, but it only accepts a Date object.

How can I convert the above timestamp+timezone into a Date object using Javascript?

Thank you for any help you can provide.

2
  • 3
    Moment accepts and in fact prefers strings. The best practice with moment is to never use a date object unless it has been given to you by a third party API. MOment should parse this time format by default when you pass it to the moment constructor. Commented Jul 24, 2016 at 14:13
  • 2
    See parsing strings: momentjs.com/docs/#/parsing/string Commented Jul 24, 2016 at 14:13

2 Answers 2

11
new Date(dateString.replace(' ', 'T'));
Sign up to request clarification or add additional context in comments.

3 Comments

some conversion of date is invalid.
@ManoharsinhRana: can you please clarify why this code would fail to convert some date strings / create an invalid conversion? Perhaps the confusion is that the O.P. stated that they needed to have this function work with a PG Timestamps WITH timezone... when their example shows +0, which is how Postgres stores timestamps without timezones (UTC / Unix Compatible). Thanks! Interested to hear your response!
why replace space with T? there's no space in OP's timestamp string.
1

I needed to use moment(some_date).fromNow()

Instead of moment.startOf(some_date).fromNow()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.