[SOLVED] Date.now() and Moment.js

Hi everyone,

Just a quick one.

I’m wanting to convert my timestamp captured using Date.now() into readable dates and times using momentjs.

Here is my simple JS so far:

var userProfile = Profiles.findOne({ username: this.props.users.username });
var dateString = moment.unix( userProfile.createdAt ).format("DD/MM/YYYY HH:mm");
return dateString;

However, this returns the following (as an example):

23/04/48272 13:45

We’re quite a long way from the year 48272!

Any help would be much appreciated.

Thanks,

Tom.

That’s not a Unix Timestamp (seconds since Unix Epoch) that you’re using as input. Kill the .unix and you should be good.

It looks like userProfile.createdAt is in ms (Javascript epochtime), rather than seconds (unix epochtime), given the year value.

Hi @abernix and thanks for your reply!

Just tried that and now I’m getting: Invalid date as my return.

Any ideas?

So do you have any suggestions? Times the userProfile.createdAt by 1000?

Thanks for your reply :slight_smile:

what is the value when you do console.log(userProfile.createdAt)? Personally I use new Date(Date.now()) so I have a valid date object.

From your first few paragraphs you used just Date.now()

So you should be doing…

var userProfile = Profiles.findOne({ username: this.props.users.username });
var dateString = moment( new Date(userProfile.createdAt )).format("DD/MM/YYYY HH:mm");
return dateString;

My misunderstanding. @robfallows is right. You should probably be storing your dates in the database with new Date(), not Date.now().

Alternatively, you could divide the DB value by 1000 (not multiply, as you said). moment.unix(userProfile.createdAt/1000). But this seems silly. Store the date in Mongo properly. :slight_smile:

A bit too late for that! This is an update to an existing app otherwise I would…

This solved the issue though, just dividing by 1k sorted it and it’s displaying correctly for me now. Thanks!