略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: MongoDate::__construct

2024-11-13

MongoDate::__construct

(PECL mongo >= 0.8.1)

MongoDate::__construct创建一个新的日期。

说明

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

创建一个新的日期。如果没有指定参数,将会使用当前的时间。

参数

sec

自纪元时间以来的秒数(例如 1 Jan 1970 00:00:00.000 UTC)。

usec

微秒。请注意 MongoDB 的解决方案是毫秒而不是微秒,这意味着这个值会被截成毫秒的方案。

返回值

返回该新的时间。

范例

Example #1 MongoDate::__construct() 例子

这个例子演示了用当前时间创建一个新的日期以及给定时间的新日期。

<?php

$d 
= new MongoDate();
echo 
"$d\n";
$d = new MongoDate(1234567890);
echo 
"$d\n";
$d = new MongoDate(strtotime("2009-05-01 00:00:01"));
echo 
"$d\n";

?>

以上例程的输出类似于:

0.23660600 1235685067
0.00000000 1234567890
0.00000000 1241150401

参见

add a note add a note

User Contributed Notes 1 note

up
1
gb at tekkie dot ro
5 years ago
Please note that the second parameter should be a microseconds value, not a miliseconds one, as stated in the documentation.

I am using the code below to show you what I mean:
<?php
    $example
= new \DateTime('2013-09-22T10:41:44.451999');
   
$seconds = $example->getTimestamp();

   
// this is what documentation misleads you to think is needed
   
$miliseconds = floor($example->format('u') / 1000);

   
// this is what you should really use
   
$microseconds = $example->format('u');
   
$fullToString = $example->format('Y-m-d\TH:i:s.uP');

   
$collection->insert(array(
       
'timeMicroseconds' => new \MongoDate($seconds, $microseconds),
       
'toString' => $fullToString,
    ));
   
$collection->insert(array(
       
'timeMiliseconds' => new \MongoDate($seconds, $miliseconds),
       
'toString' => $fullToString,
    ));
?>

Let's take a look in the database to see what is really stored:
{
    "_id" : ObjectId("523f07cfc2b581eb7f069b1d"),
    "timeMicroseconds" : ISODate("2013-09-22T07:41:44.451Z"),
    "toString" : "2013-09-22T10:41:44.451999+03:00"
}

{
    "_id" : ObjectId("523f07cfc2b581eb7f069b1e"),
    "timeMiliseconds" : ISODate("2013-09-22T07:41:44.000Z"),
    "toString" : "2013-09-22T10:41:44.451999+03:00"
}

官方地址:https://www.php.net/manual/en/mongodate.construct.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3