1

Hello guys I 'm storing date in mongodb. The problem that I'm facing is that the date time string that I get. I try to convert it into mongodate but it converts it to 0.00000000 2016. Here is the code

 $params['start'] = new MongoDate($params['start']);
        $params['end'] = new MongoDate($params['end']);

The string bring the date time in this form 2016-04-07 19:49:50 but after the conversion it becomes like this 0.00000000 2016. Please tell me what is it that I'm doing wrong

ceejayoz
  • 176,543
  • 40
  • 303
  • 368
garden
  • 309
  • 2
  • 4
  • 16

2 Answers2

4

Per the docs, MongoDate expects a timestamp value like 1460058590, not a string like 2016-04-07 19:49:50.

$params['start'] = new MongoDate(strtotime($params['start']));
ceejayoz
  • 176,543
  • 40
  • 303
  • 368
  • I'm converting the date like this before doing this date('Y-m-d H:i:s' , strtotime($startD)) – garden Apr 06 '16 at 15:05
  • 1
    Then you can cut out that step and just use "new MongoDate(strtotime($startD))", and it will accomplish the same concept as this answer: using the timestamp. – aaronofleonard Apr 06 '16 at 15:07
  • @garden "Doctor, it hurts when I do this!" "Well, stop doing that." And read the documentation. – ceejayoz Apr 06 '16 at 15:08
  • @garden We don't need more code. We've explained your issue, and the fix. Your MongoDate calls need to be passed a valid UNIX timestamp. – ceejayoz Apr 06 '16 at 15:10
3

The MongoDate constructor expects the time in Unix epoch seconds, not a time string.

public MongoDate::__construct ([ int $sec = time() [, int $usec = 0 ]] )

You'll need to convert your time string using strtotime or DateTime. The example code from the constructor documentation even includes an example:

$d = new MongoDate(strtotime("2009-05-01 00:00:01"));
echo "$d\n";
Mr. Llama
  • 20,202
  • 2
  • 62
  • 115