PHP日期格式转换 [英] PHP date format converting
问题描述
这是我有的:
$dateFormat = 'M d, Y';
$dateString = 'January 23, 2010';
我需要的是时间戳记 $ dateString
所以我可以这样做:
What I need is a timestamp of $dateString
so I can do this:
$newFormattedDate = date('Y-m-d', $timestamp);
我试图使用 strtotime
函数,但它尝试查找格式本身,并不总是工作。在我的情况下,我知道日期字符串和日期格式。
I tried to use strtotime
function but it tries to find out the format itself and doesn't work always. In my situation I know both the date string and date format.
如何将 $ timestamp
设置为适当的用于 date
功能?
How can I set $timestamp
to an appropriate value for use with the date
function?
编辑:我需要在Linux和Windows环境中工作。
I need this to work in both Linux and Windows environments.
编辑:解决方案必须支持PHP 4或更高版本
The solution must support PHP version 4 or higher
编辑:MySQL有一个名为 STR_TO_DATE
日期字符串和日期格式,并返回 Ymd
格式的日期字符串。 php的任何等效功能也适用于我。
MySQL has a function called STR_TO_DATE
which takes a date string and a date format and returns Y-m-d
formatted date string. Any equivalent function for php works for me also.
推荐答案
从PHP5.3开始,您可以使用DateTime API
As of PHP5.3 you can use the DateTime API
$dt = date_create_from_format('M d, Y', 'January 23, 2010');
echo date_timestamp_get($dt);
或使用OOP符号
$dt = DateTime::createFromFormat('M d, Y', 'January 23, 2010');
echo $dt->getTimestamp();
请注意,虽然PHP中有 DateTime
< 5.3,以上使用的方法不是,也可以模拟 - > getTimestamp()
与 - >格式('U')
,对于 createFromFormat()
Note that while DateTime
is available in PHP < 5.3, the methods used above are not and while you could simulate ->getTimestamp()
with ->format('U')
, there is no easy workaround for createFromFormat()
,没有简单的解决方法。另一种方法是使用<来自Zend的href =http://framework.zend.com/manual/en/zend.date.html =noreferrer> Zend_Date
框架:
An alternative would be to use Zend_Date
from Zend Framework:
$date = new Zend_Date('Feb 31, 2007', 'MM.dd.yyyy');
echo $date->get(Zend_Date::TIMESTAMP);
这篇关于PHP日期格式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!