PHP:将日期转换为秒?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1936237/
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 04:21:20  来源:igfitidea点击:

PHP: convert date into seconds?

php

提问by Usman

I've a date like Tue Dec 15 2009. How can I convert it into seconds?

我有一个像Tue Dec 15 2009这样的约会。如何将其转换为秒?

Update: How can I convert a date formatted as above to Unix timestamp?

更新:如何将上述格式的日期转换为 Unix 时间戳?

回答by Pekka

I assume by seconds you mean a UNIX timestamp.

我假设秒是指UNIX 时间戳

strtotime()should help.

strtotime()应该会有所帮助。

回答by Pascal MARTIN

You can use the strtotimefunction to convert that date to a timestamp :

您可以使用该strtotime函数将该日期转换为时间戳:

$str = 'Tue Dec 15 2009';
$timestamp = strtotime($str);

And, just to be sure, let's convert it back to a date as a string :

而且,为了确定,让我们将其转换回字符串形式的日期:

var_dump(date('Y-m-d', $timestamp));

Which gives us :

这给了我们:

string '2009-12-15' (length=10)

(Which proves strtotimedid understand our date ^^ )

(这证明strtotime确实了解我们的约会^^)





[edit 2012-05-19] as some other questions might point some readers here:Note that strtotime()is not the only solution, and that you should be able to work with the DateTimeclass, which provides some interesting features -- especially if you are using PHP >= 5.3

[edit 2012-05-19] 因为其他一些问题可能会指向这里的一些读者:请注意,这strtotime()不是唯一的解决方案,您应该能够使用DateTime该类,它提供了一些有趣的功能 - 特别是如果您正在使用PHP >= 5.3


In this case, you could use something like the following portion of code :


在这种情况下,您可以使用类似于以下代码部分的内容:

$str = 'Tue Dec 15 2009';
$format = 'D F d Y';
$dt = DateTime::createFromFormat($format, $str);
$timestamp = $dt->format('U');


DateTime::createFromFormat()allows one to create a DateTimeobject from almost any date, no matter how it's formated, as you can specify the format you date's in (This method is available with PHP >= 5.3).


DateTime::createFromFormat()允许DateTime从几乎任何日期创建对象,无论它的格式如何,因为您可以指定日期的格式(此方法适用于 PHP >= 5.3)

And DateTime::format()will allow you to format that object to almost any kind of date format -- including an UNIX Timestamp, as requested here.

并且DateTime::format()允许您将该对象格式化为几乎任何类型的日期格式 - 包括UNIX Timestamp,如此处所要求。

回答by hanse

You mean like an UNIX-timestamp? Try:

你的意思是像一个 UNIX 时间戳?尝试:

echo strtotime('Tue Dec 15 2009');