php 从毫秒获取日期格式 mdY H:i:su

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17909871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:39:23  来源:igfitidea点击:

getting date format m-d-Y H:i:s.u from milliseconds

php

提问by slik

I am trying to get a formatted date, including the microseconds from milliseconds.

我正在尝试获取格式化的日期,包括从毫秒开始的微秒。

The only problem is I keep getting 000000

唯一的问题是我不断收到 000000

date("m-d-Y H:i:s.u", $milliseconds/1000);

ex. 07-28-2013 11:26:14.000000

前任。07-28-2013 11:26:14.000000

回答by ArchCodeMonkey

You can readily do this this with the input format U.u.

您可以使用输入格式轻松地做到这一点U.u

$now = DateTime::createFromFormat('U.u', microtime(true));
echo $now->format("m-d-Y H:i:s.u");

This produces the following output:

这会产生以下输出:

04-13-2015 05:56:22.082300

From the PHP manual page for date formats:

来自日期格式的 PHP 手册页:

  • U = Seconds since the Unix Epoch
  • u = Microseconds
  • U = 自 Unix 时代以来的秒数
  • u = 微秒

http://php.net/manual/en/function.date.php

http://php.net/manual/en/function.date.php



Thanks goes to giggsey for pointing out a flaw in my original answer, adding number_format()to the line should fix the case of the exact second. Too bad it doesn't feel quite as elegant any more...

感谢 giggsey 指出我原始答案中的一个缺陷,添加number_format()到该行应该可以解决确切秒的情况。太糟糕了,它感觉不再那么优雅了......

$now = DateTime::createFromFormat('U.u', number_format(microtime(true), 6, '.', ''));

http://php.net/manual/en/function.number-format.php

http://php.net/manual/en/function.number-format.php



A note on time zones in response to DaVe.

响应 DaVe 的时区注释。

Normally the createFromFormat()method will use the local time zone if one is not specified.

通常,createFromFormat()如果未指定,该方法将使用本地时区。

http://php.net/manual/en/datetime.createfromformat.php

http://php.net/manual/en/datetime.createfromformat.php

However, the technique described here is initialising the DateTime object using microtime()which returns the number of seconds elapsed since the Unix Epoch (01 Jan 1970 00:00:00 GMT).

然而,这里描述的技术是初始化 DateTime 对象,使用microtime()它返回自 Unix 纪元(1970 年 1 月 1 日 00:00:00 GMT)以来经过的秒数。

http://php.net/manual/en/function.microtime.php

http://php.net/manual/en/function.microtime.php

This means that the DateTime object is implicitly initialised to UTC, which is fine for server internal tasks that just want to track elapsed time.

这意味着 DateTime 对象被隐式初始化为 UTC,这对于只想跟踪经过时间的服务器内部任务来说很好。

If you need to display the time for a particular time zone then you need to set it accordingly. However, this should be done as a separate step after the initialisation (notusing the third parameter of createFromFormat()) because of the reasons discussed above.

如果您需要显示特定时区的时间,则需要相应地进行设置。但是,由于上述原因,这应该在初始化之后作为一个单独的步骤完成(使用的第三个参数createFromFormat())。

The setTimeZone()method can be used to accomplish this requirement.

setTimeZone()方法可用于完成此要求。

http://php.net/manual/en/datetime.settimezone.php

http://php.net/manual/en/datetime.settimezone.php

As an example:

举个例子:

$now = DateTime::createFromFormat('U.u', number_format(microtime(true), 6, '.', ''));
echo $now->format("m-d-Y H:i:s.u") . '<br>';

$local = $now->setTimeZone(new DateTimeZone('Australia/Canberra'));
echo $local->format("m-d-Y H:i:s.u") . '<br>';

Produces the following output:

产生以下输出:

10-29-2015 00:40:09.433818
10-29-2015 11:40:09.433818


Note that if you want to input into mysql, the time format needs to be:

注意如果要输入mysql,时间格式需要为:

format("Y-m-d H:i:s.u")

回答by Marin Sagovac

php.netsays:

php.net说:

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

微秒(在 PHP 5.2.2 中添加)。请注意,date()它将始终生成,000000因为它采用整数参数,而DateTime::format()如果DateTime使用微秒创建,则支持微秒。

So use as simple:

所以使用简单:

$micro_date = microtime();
$date_array = explode(" ",$micro_date);
$date = date("Y-m-d H:i:s",$date_array[1]);
echo "Date: $date:" . $date_array[0]."<br>";

Recommended and use dateTime()class from referenced:

推荐和使用dateTime()类来自参考:

$t = microtime(true);
$micro = sprintf("%06d",($t - floor($t)) * 1000000);
$d = new DateTime( date('Y-m-d H:i:s.'.$micro, $t) );

print $d->format("Y-m-d H:i:s.u"); // note at point on "u"

Note uis microseconds (1 seconds = 1000000 μs).

注意u是微秒(1 秒 = 1000000 微秒)。

Another example from php.net:

来自php.net 的另一个例子:

$d2=new DateTime("2012-07-08 11:14:15.889342");

Reference of dateTime()on php.net

参考dateTime()php.net

I've answered on question as short and simplify to author. Please see for more information to author: getting date format m-d-Y H:i:s.u from milliseconds

我已经回答了简短的问题并简化了作者。请参阅作者的更多信息:从毫秒获取日期格式 mdY H:i:su

回答by thotso

Here's a slightly shorter approach. Rather than work to create a high-precision numeric date/time, I convert the microsecond value to a string, remove the 0, and add it to the end of the date/time string. I can easily trim the number of decimals by adjusting the string length parameter; here I use 4to get milliseconds, but you could use 7to get microseconds.

这是一个稍微短一点的方法。我没有创建高精度数字日期/时间,而是将微秒值转换为字符串,删除0,并将其添加到日期/时间字符串的末尾。我可以通过调整字符串长度参数轻松修剪小数位数;在这里我4用来获取毫秒,但你可以7用来获取微秒。

$t = explode(" ",microtime());
echo date("m-d-y H:i:s",$t[1]).substr((string)$t[0],1,4);

For a microtime() value of 0.98236000 1407400573, this returns 08-07-14 01:08:13.982.

对于 microtime() 值0.98236000 1407400573,这将返回08-07-14 01:08:13.982

回答by bamossza

I'm use

我在用

echo date("Y-m-d H:i:s.").gettimeofday()["usec"];

output: 2017-09-05 17:04:57.555036

回答by ghbarratt

echo date('m-d-Y H:i:s').substr(fmod(microtime(true), 1), 1);

example output:

示例输出:

02-06-2019 16:45:03.53811192512512

If you have a need to limit the number of decimal places then the below line (credit mgutt) would be a good alternative. (With the code below, the 6 limits the number of decimal places to 6.)

如果您需要限制小数位数,那么下面的行(credit mgutt)将是一个不错的选择。(在下面的代码中,6 将小数位数限制为 6。)

echo date('m-d-Y H:i:').sprintf('%09.6f', date('s')+fmod(microtime(true), 1));

example output:

示例输出:

02-11-2019 15:33:03.624493

回答by SDpyro

Here is another method that I find slightly more elegant/simple:

这是我发现稍微优雅/简单的另一种方法:

echo date('Y-m-d-H:i:s.').preg_replace("/^.*\./i","", microtime(true));

回答by John Kearney

This is based on answer from ArchCodeMonkey.

这是基于 ArchCodeMonkey 的回答。

But just simplified, if you just want something quick that works.

但只是简化了,如果你只是想要一些快速有效的东西。

function DateTime_us_utc(){
    return DateTime::createFromFormat('U.u', number_format(microtime(true), 6, '.', ''));
}
function DateTime_us(){
    $now = DateTime_us_utc();
    return $now->setTimeZone(new DateTimeZone(date_default_timezone_get()));
}

So for me then

所以对我来说

$now = DateTime_us();
$now->format("m-d-Y H:i:s.u");

回答by mpen

If you want to format a date like JavaScript's (new Date()).toISOString()for some reason, this is how you can do it in PHP:

如果您(new Date()).toISOString()出于某种原因想像 JavaScript 那样格式化日期,您可以在 PHP 中这样做:

$now = microtime(true);
gmdate('Y-m-d\TH:i:s', $now).sprintf('.%03dZ',round(($now-floor($now))*1000));

Sample output:

示例输出:

2016-04-27T18:25:56.696Z


Just to prove that subtracting off the whole number doesn't reduce the accuracy of the decimal portion:

只是为了证明减去整数不会降低小数部分的准确性:

>>> number_format(123.01234567890123456789,25)
=> "123.0123456789012408307826263"
>>> number_format(123.01234567890123456789-123,25)
=> "0.0123456789012408307826263"

PHP didround the decimal places, but it rounded them the same way in both cases.

PHP确实对小数位进行了四舍五入,但在两种情况下都以相同的方式四舍五入。

回答by Geo

// Procedural
$fineStamp = date('Y-m-d\TH:i:s') . substr(microtime(), 1, 9);
echo $fineStamp . PHP_EOL;

// Object-oriented (if you must). Still relies on $fineStamp though :-\
$d = new DateTime($fineStamp);
echo $d->format('Y-m-d\TH:i:s.u') . PHP_EOL;

回答by Harveyhase68

As of PHP 7.1 you can simply do this:

从 PHP 7.1 开始,您可以简单地执行以下操作:

$date = new DateTime( "NOW" );
echo $date->format( "m-d-Y H:i:s.u" );

It will display as:

它将显示为:

04-11-2018 10:54:01.321688