2

How do I convert a String like "11/21/2012" to Date in MongoDB?

I tried the following

obj.as_from = ISODate("11/21/2012");

and got this error

uncaught exception: invalid ISO date

Is there a simple way to convert the string above?

Julian
  • 1,853
  • 5
  • 27
  • 48

2 Answers2

4

As pointed by user602525, in the Mongo shell.

obj.as_from = new Date("11/21/2012");

Do not forget to use the new operator.

Rafa Viotti
  • 9,998
  • 4
  • 42
  • 62
  • Ok this works, any idea how to handle a string like "11/2012"? One that only shows the month and year. When I try that it defaults to 1970. – Julian Dec 26 '13 at 03:43
  • 1
    In this case I would parse the date string manually and use the Date constructor: `new Date(2012, 10)`. Months start from zero in JavaScript. – Rafa Viotti Dec 26 '13 at 03:51
  • Thanks again. I notice the day deaults to "01". Is there a way to get it to default to "00" to represent nothing? – Julian Dec 26 '13 at 04:45
  • 1
    A date represents some given fixed point in time. Without a day number it just wouldn't be a date and you'd better stick with a string. – Calimero Dec 26 '13 at 08:04
  • @Calimero that's what I was thinking. I actually have two dates in the document. One with a short month/year format and one that is more detailed. I just convert the detailed one and the the short format as a string. – Julian Dec 26 '13 at 16:22
0

You try doing like that:

ISODate("11-21-2012T05:00:00.000Z")

Hao Luong
  • 92
  • 1
  • 4