日期时间(以微秒为单位) [英] DateTime with microseconds

查看:501
本文介绍了日期时间(以微秒为单位)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码中,我使用DateTime对象处理日期,然后将其转换为时间戳,以便将其保存在某些JSON文件中.

出于某些原因,我想拥有与DateTime相同的东西(或接近的东西),但是具有微秒级的精度(在插入JSON文件内部时,我会转换为float.)

我的问题是:是否有一个像DateTime这样的 PHP对象,但是也可以处理 microseconds 吗?

目标是能够对对象进行微操作.

date()文档中,有一些内容指示DateTime可以用微秒创建,但我找不到方法.

u微秒(已在PHP 5.2.2中添加).请注意,date()将始终 由于它需要一个整数参数,因此会生成000000,而 如果创建了DateTime,则DateTime :: format()确实支持微秒 只需几微秒.

我试图用浮动值(microtime(true))设置DateTime对象的时间戳,但是它不起作用(我认为它将时间戳转换为int,造成微秒的损失). /p>

这是我尝试的方式

$dt = new DateTime();
$dt->setTimestamp(3.4); // I replaced 3.4 by microtime(true), this is just to give an example
var_dump($dt);
var_dump($dt->format('u'));

如您在此处看到的,未考虑.4(即使我们可以使用u格式,它对应于微秒).

object(DateTime)[1]
  public 'date' => string '1970-01-01 01:00:03' (length=19)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Europe/Berlin' (length=13)

string '000000' (length=6)

我看到了这段代码,该代码允许将微秒添加到DateTime,但是在创建DateTime之前,我需要对微时进行大量修改.由于我将大量使用它,因此我想在获取微时对象"之前对微时进行尽可能少的修改.

$d = new DateTime("15-07-2014 18:30:00.111111");

解决方案

/!\编辑/!\

我现在使用 https://github.com/briannesbitt/Carbon ,其余部分出于历史原因,答案就在这里.

结束编辑

我决定使用大家都给我的提示来扩展DateTime类.

构造函数采用浮点数(来自microtime)或不作任何选择(在这种情况下,它将使用当前的微时间戳"进行初始化). 我还覆盖了两个重要的功能:setTimestampgetTimestamp.

不幸的是,尽管它并没有我想象的那么慢,但是我无法解决表演问题.

这是整个班级:

<?php
class MicroDateTime extends DateTime
{
    public $microseconds = 0;

    public function __construct($time = 'now')
    {
        if ($time == 'now')
            $time = microtime(true);

        if (is_float($time + 0)) // "+ 0" implicitly converts $time to a numeric value
        {
            list($ts, $ms) = explode('.', $time);
            parent::__construct(date('Y-m-d H:i:s.', $ts).$ms);
            $this->microseconds = $time - (int)$time;
        }
        else
            throw new Exception('Incorrect value for time "'.print_r($time, true).'"');
    }

    public function setTimestamp($timestamp)
    {
        parent::setTimestamp($timestamp);
        $this->microseconds = $timestamp - (int)$timestamp;
    }

    public function getTimestamp()
    {
        return parent::getTimestamp() + $this->microseconds;
    }
}

In my code, I'm using DateTime objects to manipulate dates, then convert them to timestamp in order to save them in some JSON files.

For some reasons, I want to have the same thing as DateTime (or something close), but with microseconds precision (that I would convert to float when inserting inside the JSON files).

My question is : is there a PHP object that is like DateTime, but can handle microseconds too ?

The goal is to be able to manipulate microtimes with objects.

In the date() documentation, there is something that indicates that DateTime can be created with microseconds, but I wasn't able to find how.

u Microseconds (added in PHP 5.2.2). Note that date() will always generate 000000 since it takes an integer parameter, whereas DateTime::format() does support microseconds if DateTime was created with microseconds.

I have tried to set the timestamp of a DateTime object with a floating value (microtime(true)), but it doesn't work (I think it converts the timestamp to an int, causing the loss of the microseconds).

Here is how i tried

$dt = new DateTime();
$dt->setTimestamp(3.4); // I replaced 3.4 by microtime(true), this is just to give an example
var_dump($dt);
var_dump($dt->format('u'));

The .4 is not taken into account as you can see here (even though we can use the u format, which corresponds to the microseconds).

object(DateTime)[1]
  public 'date' => string '1970-01-01 01:00:03' (length=19)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Europe/Berlin' (length=13)

string '000000' (length=6)

EDIT : I saw this code, which allows to add microseconds to a DateTime, but I would need to apply a lot of modifications to the microtime before creating the DateTime. Since I will use this a lot, I want to do as little modifications to the microtime as possible before getting the "microtime object".

$d = new DateTime("15-07-2014 18:30:00.111111");

解决方案

/!\ EDIT /!\

I now use https://github.com/briannesbitt/Carbon, the rest of this answer is just here for historical reasons.

END EDIT

I decided to extend the class DateTime using the tips you all gave me.

The constructor takes a float (from microtime) or nothing (in this case it will be initialized with the current "micro-timestamp"). I also overrided 2 functions that were important : setTimestamp and getTimestamp.

Unfortunately, I couldn't solve the performances issue, although it's not as slow as I thought.

Here's the whole class :

<?php
class MicroDateTime extends DateTime
{
    public $microseconds = 0;

    public function __construct($time = 'now')
    {
        if ($time == 'now')
            $time = microtime(true);

        if (is_float($time + 0)) // "+ 0" implicitly converts $time to a numeric value
        {
            list($ts, $ms) = explode('.', $time);
            parent::__construct(date('Y-m-d H:i:s.', $ts).$ms);
            $this->microseconds = $time - (int)$time;
        }
        else
            throw new Exception('Incorrect value for time "'.print_r($time, true).'"');
    }

    public function setTimestamp($timestamp)
    {
        parent::setTimestamp($timestamp);
        $this->microseconds = $timestamp - (int)$timestamp;
    }

    public function getTimestamp()
    {
        return parent::getTimestamp() + $this->microseconds;
    }
}

这篇关于日期时间(以微秒为单位)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆