在 PHP 中将一种日期格式转换为另一种格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2167916/
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
Convert one date format into another in PHP
提问by Tom
Is there a simple way to convert one date format into another date format in PHP?
有没有一种简单的方法可以在 PHP 中将一种日期格式转换为另一种日期格式?
I have this:
我有这个:
$old_date = date('y-m-d-h-i-s'); // works
$middle = strtotime($old_date); // returns bool(false)
$new_date = date('Y-m-d H:i:s', $middle); // returns 1970-01-01 00:00:00
But I'd of course like it to return a current date rather than the crack 'o dawn. What am I doing wrong?
但我当然希望它返回当前日期而不是黎明。我究竟做错了什么?
采纳答案by Pekka
The second parameter to date()needs to be a proper timestamp (seconds since January 1, 1970). You are passing a string, which date() can't recognize.
第二个参数 todate()需要是一个正确的时间戳(自 1970 年 1 月 1 日以来的秒数)。您正在传递一个字符串,而 date() 无法识别该字符串。
You can use strtotime()to convert a date string into a timestamp. However, even strtotime() doesn't recognize the y-m-d-h-i-sformat.
您可以使用strtotime()将日期字符串转换为时间戳。但是,即使 strtotime() 也无法识别y-m-d-h-i-s格式。
PHP 5.3 and up
PHP 5.3 及更高版本
Use DateTime::createFromFormat. It allows you to specify an exact mask - using the date()syntax - to parse incoming string dates with.
使用DateTime::createFromFormat. 它允许您指定一个精确的掩码 - 使用date()语法 - 来解析传入的字符串日期。
PHP 5.2 and lower
PHP 5.2 及更低版本
You will have to parse the elements (year, month, day, hour, minute, second) manually using substr()and hand the results to mktime()that will build you a timestamp.
您将必须使用手动解析元素(年、月、日、小时、分钟、秒)substr()并将结果传递给mktime(),这将为您构建时间戳。
But that's a lot of work! I recommend using a different format that strftime() can understand. strftime() understands anydate input short of the next time joe will slip on the ice. for example, this works:
但这是很多工作!我建议使用 strftime() 可以理解的不同格式。strftime() 可以理解任何没有the next time joe will slip on the ice. 例如,这有效:
$old_date = date('l, F d y h:i:s'); // returns Saturday, January 30 10 02:06:34
$old_date_timestamp = strtotime($old_date);
$new_date = date('Y-m-d H:i:s', $old_date_timestamp);
回答by ceiroa
The easiest way to do this is
最简单的方法是
$myDateTime = DateTime::createFromFormat('Y-m-d', $dateString);
$newDateString = $myDateTime->format('m/d/Y');
You are first giving it the format $dateString is in. Then you are telling it the format you want $newDateString to be in.
你首先给它 $dateString 的格式。然后你告诉它你想要 $newDateString 的格式。
This also avoids the use of strtotime, which can be hard to work with at times.
这也避免了 strtotime 的使用,它有时很难使用。
If you are not transforming from one date format to another, but just want the current date (or datetime) in a specific format then it's even easier:
如果您不是从一种日期格式转换为另一种日期格式,而只是想要特定格式的当前日期(或日期时间),那么它会更容易:
$now = new DateTime();
$timestring = $now->format('Y-m-d h:i:s');
This other question also refers to the same topic: Convert date format yyyy-mm-dd => dd-mm-yyyy.
另一个问题也涉及同一主题:转换日期格式 yyyy-mm-dd => dd-mm-yyyy。
回答by John Conde
The Basics
基础知识
The simplist way to convert one date format into another is to use strtotime()with date(). strtotime()will convert the date into a Unix Timestamp. That Unix Timestamp can then be passed to date()to convert it to the new format.
将一种日期格式转换为另一种日期格式的最简单方法是使用strtotime()with date()。strtotime()将日期转换为Unix Timestamp。然后可以传递该 Unix 时间戳date()以将其转换为新格式。
$timestamp = strtotime('2008-07-01T22:35:17.02');
$new_date_format = date('Y-m-d H:i:s', $timestamp);
Or as a one-liner:
或者作为单线:
$new_date_format = date('Y-m-d H:i:s', strtotime('2008-07-01T22:35:17.02'));
Keep in mind that strtotime()requires the date to be in a valid format. Failure to provide a valid format will result in strtotime()returning false which will cause your date to be 1969-12-31.
请记住,这strtotime()要求日期采用有效格式。未能提供有效格式将导致strtotime()返回 false,这将导致您的日期为 1969-12-31。
Using DateTime()
使用 DateTime()
As of PHP 5.2, PHP offered the DateTime()class which offers us more powerful tools for working with dates (and time). We can rewrite the above code using DateTime()as so:
从 PHP 5.2 开始,PHP 提供了一个DateTime()类,它为我们提供了更强大的工具来处理日期(和时间)。我们可以这样重写上面的代码DateTime():
$date = new DateTime('2008-07-01T22:35:17.02');
$new_date_format = $date->format('Y-m-d H:i:s');
Working with Unix timestamps
使用 Unix 时间戳
date()takes a Unix timeatamp as its second parameter and returns a formatted date for you:
date()将 Unix 时间戳作为其第二个参数并为您返回格式化的日期:
$new_date_format = date('Y-m-d H:i:s', '1234567890');
DateTime() works with Unix timestamps by adding an @before the timestamp:
DateTime() 通过@在时间戳前添加一个来处理 Unix时间戳:
$date = new DateTime('@1234567890');
$new_date_format = $date->format('Y-m-d H:i:s');
If the timestamp you have is in milliseconds (it may end in 000and/or the timestamp is thirteen characters long) you will need to convert it to seconds before you can can convert it to another format. There's two ways to do this:
如果您拥有的时间戳以毫秒为单位(它可能以毫秒结尾000和/或时间戳为 13 个字符长),您需要先将其转换为秒,然后才能将其转换为另一种格式。有两种方法可以做到这一点:
- Trim the last three digits off using
substr()
- 使用修剪掉最后三位数字
substr()
Trimming the last three digits can be acheived several ways, but using substr()is the easiest:
修剪最后三位数字可以通过多种方式实现,但使用substr()是最简单的:
$timestamp = substr('1234567899000', -3);
- Divide the substr by 1000
- 将 substr 除以 1000
You can also convert the timestamp into seconds by dividing by 1000. Because the timestamp is too large for 32 bit systems to do math on you will need to use the BCMathlibrary to do the math as strings:
您还可以通过除以 1000 将时间戳转换为秒。由于时间戳对于 32 位系统来说太大而无法进行数学运算,因此您需要使用BCMath库以字符串形式进行数学运算:
$timestamp = bcdiv('1234567899000', '1000');
To get a Unix Timestamp you can use strtotime()which returns a Unix Timestamp:
要获得 Unix 时间戳,您可以使用strtotime()它返回 Unix 时间戳:
$timestamp = strtotime('1973-04-18');
With DateTime() you can use DateTime::getTimestamp()
使用 DateTime() 您可以使用 DateTime::getTimestamp()
$date = new DateTime('2008-07-01T22:35:17.02');
$timestamp = $date->getTimestamp();
If you're running PHP 5.2 you can use the Uformatting option instead:
如果您运行的是 PHP 5.2,则可以改用U格式化选项:
$date = new DateTime('2008-07-01T22:35:17.02');
$timestamp = $date->format('U');
Working with non-standard and ambiguous date formats
使用非标准和不明确的日期格式
Unfortunately not all dates that a developer has to work with are in a standard format. Fortunately PHP 5.3 provided us with a solution for that. DateTime::createFromFormat()allows us to tell PHP what format a date string is in so it can be successfully parsed into a DateTime object for further manipulation.
不幸的是,并非开发人员必须使用的所有日期都采用标准格式。幸运的是 PHP 5.3 为我们提供了解决方案。DateTime::createFromFormat()允许我们告诉 PHP 日期字符串的格式,以便它可以成功解析为 DateTime 对象以供进一步操作。
$date = DateTime::createFromFormat('F-d-Y h:i A', 'April-18-1973 9:48 AM');
$new_date_format = $date->format('Y-m-d H:i:s');
In PHP 5.4 we gained the ability to do class member access on instantiation has been added which allows us to turn our DateTime()code into a one-liner:
在 PHP 5.4 中,我们获得了在实例化时访问类成员的能力,这允许我们将DateTime()代码变成单行代码:
$new_date_format = (new DateTime('2008-07-01T22:35:17.02'))->format('Y-m-d H:i:s');
$new_date_format = DateTime::createFromFormat('F-d-Y h:i A', 'April-18-1973 9:48 AM')->format('Y-m-d H:i:s');
回答by Sarfraz
Try this:
尝试这个:
$old_date = date('y-m-d-h-i-s');
$new_date = date('Y-m-d H:i:s', strtotime($old_date));
回答by Jelle de Fries
To convert $datefrom dd-mm-yyyy hh:mm:ssto a proper MySQL datetime
I go like this:
要转换$date从dd-mm-yyyy hh:mm:ss到一个适当的MySQL日期时间我是这样的:
$date = DateTime::createFromFormat('d-m-Y H:i:s',$date)->format('Y-m-d H:i:s');
回答by Peter
The following is an easy method to convert dates to different formats.
以下是将日期转换为不同格式的简单方法。
// Create a new DateTime object
$date = DateTime::createFromFormat('Y-m-d', '2016-03-25');
// Output the date in different formats
echo $date->format('Y-m-d')."\n";
echo $date->format('d-m-Y')."\n";
echo $date->format('m-d-Y')."\n";
回答by Rifat
$old_date = date('y-m-d-h-i-s'); // works
you are doing wrong here, this should be
你在这里做错了,这应该是
$old_date = date('y-m-d h:i:s'); // works
separator of time is ':'
时间分隔符是':'
I think this will help...
我认为这会有所帮助...
$old_date = date('y-m-d-h-i-s'); // works
preg_match_all('/(\d+)-(\d+)-(\d+)-(\d+)-(\d+)-(\d+)/', $old_date, $out, PREG_SET_ORDER);
$out = $out[0];
$time = mktime($out[4], $out[5], $out[6], $out[2], $out[3], $out[1]);
$new_date = date('Y-m-d H:i:s', $time);
OR
或者
$old_date = date('y-m-d-h-i-s'); // works
$out = explode('-', $old_date);
$time = mktime($out[3], $out[4], $out[5], $out[1], $out[2], $out[0]);
$new_date = date('Y-m-d H:i:s', $time);
回答by John Parker
You need to convert the $old_date back into a timestamp, as the date functionrequires a timestamp as its second argument.
您需要将 $old_date 转换回时间戳,因为date 函数需要时间戳作为其第二个参数。
回答by de_nuit
strtotime will work that out. the dates are just not the same and all in us-format.
strtotime 会解决这个问题。日期只是不一样,都是美国格式。
<?php
$e1 = strtotime("2013-07-22T12:00:03Z");
echo date('y.m.d H:i', $e1);
echo "2013-07-22T12:00:03Z";
$e2 = strtotime("2013-07-23T18:18:15Z");
echo date ('y.m.d H:i', $e2);
echo "2013-07-23T18:18:15Z";
$e1 = strtotime("2013-07-21T23:57:04Z");
echo date ('y.m.d H:i', $e2);
echo "2013-07-21T23:57:04Z";
?>
回答by Nishad Up
This native way will help to convert any inputted format to the desired format.
这种原生方式将有助于将任何输入的格式转换为所需的格式。
$formatInput = 'd-m-Y'; //Give any format here, this would be converted into your format
$dateInput = '01-02-2018'; //date in above format
$formatOut = 'Y-m-d'; // Your format
$dateOut = DateTime::createFromFormat($formatInput, $dateInput)->format($formatOut);

