arg_stack
arg_stack

Reputation: 11

mongodb date storage in MM/DD/YYYY

i am trying to store date in mm/dd/YYYY format to achieve that i tried following things in mongoShell

dt=new Date(2012,01,01)
ISODate("2012-01-31T18:30:00Z")

which is not my desirable format. I am trying to store it as ISODate("2012-01-01") so that i can use between , greater than less than kind of comparison to fetch my desirable data from mongoDB.

Upvotes: 1

Views: 3040

Answers (2)

Faiz Mohamed Haneef
Faiz Mohamed Haneef

Reputation: 3596

One possible solution is to store in the below format

{
  year : 2016,
  month: 1,
  day: 1,
  yymmdd : 20160001
}
{
  year : 2015,
  month: 10,
  day: 20,
  yymmdd : 20151020
}

yymmdd is
year multiplied by 10,000
month multiplied by 100 and added with date

So Jan - 1 2016 would be 2016x10000 + 0x100 +1 = 20160001
Nov-20 2015 would be 2015x10000 + 10*100 + 25 = 20151025

and so forth

The above design would enable sorting from 0AD to 9999AD

Date is a 64bit integer, so if you are using the yyyymmdd style(as above) its a 32bit integer, saves your space and serves your purpose

Upvotes: 1

Asya Kamsky
Asya Kamsky

Reputation: 42362

Sounds like your question is about how to convert the ISO date that you store in Mongo into a string. I'm sure you can work out the proper syntax for Java, but in Mongo shell you can do it simply like this:

> d=new Date(2012,01,01)
ISODate("2012-02-01T05:00:00Z")
> print ( d.getFullYear()+"/"+d.getMonth()+"/"+d.getDate() )
2012/1/1

But note that you get back the number you passed to Date and not the number reflecting the month it is. To solve that you can use d.toLocaleDateString()

> d.toLocaleDateString()
02/01/2012

This is because JavaScript Date function takes (and returns) 0-based months and you also want to make sure you are careful about the timezone relative to UTC/GMT time zone.

Upvotes: 0

Related Questions