在我的代码中,我使用DateTime对象来操作日期,然后将它们转换为时间戳,以便将它们保存在一些JSON文件中.
出于某些原因,我希望与DateTime(或接近的东西)具有相同的功能,但具有微秒精度(我在插入JSON文件时将转换为float).
我的问题是:是否有一个PHP对象就是喜欢DateTime,但能处理微秒吗?
目标是能够使用对象操纵microtimes.
在date()文档中,有一些东西表明可以用微秒创建DateTime,但我无法找到如何.
u微秒(在PHP 5.2.2中添加).请注意,date()将始终生成000000,因为它采用整数参数,而DateTime :: format()确实支持微秒,如果使用微秒创建DateTime.
我曾尝试使用浮点值(microtime(true))设置DateTime对象的时间戳,但它不起作用(我认为它将时间戳转换为int,导致丢失微秒).
这是我试过的方式
$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'));
Run Code Online (Sandbox Code Playgroud)
这里.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)
Run Code Online (Sandbox Code Playgroud)
编辑:我看到这个代码,它允许在DateTime中添加微秒,但我需要在创建DateTime之前对microtime应用大量修改.由于我将使用它很多,我想在获得"microtime对象"之前尽可能少地修改microtime.
$d = new DateTime("15-07-2014 18:30:00.111111");
Run Code Online (Sandbox Code Playgroud) 我有这个PHP
<?php echo round($price, 2); ?>
Run Code Online (Sandbox Code Playgroud)
和$price可能1.0000
我想,1.00但我只得到1
有任何想法吗
我正在使用sprintf()来获取具有一定精度的一些浮点数的格式化字符串.另外,我想添加前导零以使所有数字均匀.对整数执行此操作非常简单:
sprintf('%02d', 1);
Run Code Online (Sandbox Code Playgroud)
这将导致01.但是,对具有精度的浮点执行相同操作不起作用:
sprintf('%02.2f', 1);
Run Code Online (Sandbox Code Playgroud)
收益率1.00.
如何将前导零添加到浮点值?
如果我有一个 DateTime 类型的对象,如何添加一些毫秒?
$date = new Datetime("2016-09-23T20:48:16.090Z");
// how to add to this date 9 milliseconds?
Run Code Online (Sandbox Code Playgroud)