ackuser
ackuser

Reputation: 5879

How can I create a ISODate() from timestamp in MongoDB?

I am trying to create a ISODate() from a timestamp but I was unable.

I mean, imagine you want to get current date less 7 days, then what I would do is something like

ISODate(ISODate().getTime() - 1000 * 3600 * 24 * 7).toISOString().substring(0,10)

And it is okay, however I am getting 1464-10-23 so...

I am trying to do it without new Date()!

It is important to me because, it is the only way I can do the query that I need (I have dd/mm/yyyy string dates on the DB) with an aggregation as a far as I know (I am very beginner on mongo)

Upvotes: 1

Views: 3554

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311835

Your solution doesn't work because the ISODate constructor only takes a string parameter, not a timestamp. However, you can use Date in the shell instead:

> new Date((new Date()).getTime() - 1000 * 3600 * 24 * 7).toISOString().substring(0,10)
2016-05-24

Date objects in the shell are wrapped by ISODate, so this should still work for whatever you want to do.

> new Date((new Date()).getTime() - 1000 * 3600 * 24 * 7)
ISODate("2016-05-24T15:31:48.335Z")

Upvotes: 2

Related Questions