php 将字符串转换为日期和日期时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6238992/
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
Converting string to Date and DateTime
提问by Chris Pinski
If I have a PHP string in the format of mm-dd-YYYY
(for example, 10-16-2003), how do I properly convert that to a Date
and then a DateTime
in the format of YYYY-mm-dd
? The only reason I ask for both Date
and DateTime
is because I need one in one spot, and the other in a different spot.
如果我有一个格式为mm-dd-YYYY
(例如 10-16-2003)的 PHP 字符串,我该如何正确地将其转换为 aDate
和 aDateTime
格式YYYY-mm-dd
?我问两个唯一的原因Date
,并DateTime
是因为我需要一个在一个地方,和其他在不同的地方。
回答by Ibu
Use strtotime()
on your first date then date('Y-m-d')
to convert it back:
strtotime()
在第一次约会时使用,然后date('Y-m-d')
将其转换回来:
$time = strtotime('10/16/2003');
$newformat = date('Y-m-d',$time);
echo $newformat;
// 2003-10-16
Make note that there is a difference between using forward slash /
and hyphen -
in the strtotime()
function. To quote from php.net:
请注意,在函数中使用正斜杠/
和连字符是有区别-
的strtotime()
。引用 php.net:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.
To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.
m/d/y 或 dmy 格式的日期通过查看各个组件之间的分隔符来消除歧义:如果分隔符是斜杠 (/),则假定为美国 m/d/y;而如果分隔符是破折号 (-) 或点 (.),则假定为欧洲 dmy 格式。
为避免潜在的歧义,最好尽可能使用 ISO 8601 (YYYY-MM-DD) 日期或 DateTime::createFromFormat()。
回答by Matthew
You need to be careful with m/d/Y and m-d-Y formats. PHP considers /
to mean m/d/Y and -
to mean d-m-Y. I would explicitly describe the input format in this case:
您需要小心 m/d/Y 和 mdY 格式。PHP 认为/
表示 m/d/Y 和-
表示 dmY。在这种情况下,我会明确描述输入格式:
$ymd = DateTime::createFromFormat('m-d-Y', '10-16-2003')->format('Y-m-d');
That way you are not at the whims of a certain interpretation.
这样你就不会随心所欲地做出某种解释。
回答by user2707671
To parse the date, you should use: DateTime::createFromFormat();
要解析日期,您应该使用: DateTime::createFromFormat();
Ex:
前任:
$dateDE = "16/10/2013";
$dateUS = \DateTime::createFromFormat("d.m.Y", $dateDE)->format("m/d/Y");
However, careful, because this will crash with:
但是,请小心,因为这会导致崩溃:
PHP Fatal error: Call to a member function format() on a non-object
You actually need to check that the formatting went fine, first:
您实际上需要首先检查格式是否正常:
$dateDE = "16/10/2013";
$dateObj = \DateTime::createFromFormat("d.m.Y", $dateDE);
if (!$dateObj)
{
throw new \UnexpectedValueException("Could not parse the date: $date");
}
$dateUS = $dateObj->format("m/d/Y");
Now instead of crashing, you will get an exception, which you can catch, propagate, etc.
现在,您将得到一个异常,而不是崩溃,您可以捕获、传播等。
$dateDE has the wrong format, it should be "16.10.2013";
$dateDE 格式错误,应该是“16.10.2013”;
回答by N.B.
$d = new DateTime('10-16-2003');
$timestamp = $d->getTimestamp(); // Unix timestamp
$formatted_date = $d->format('Y-m-d'); // 2003-10-16
Edit: you can also pass a DateTimeZone to DateTime() constructor to ensure the creation of the date for the desired time zone, not the server default one.
编辑:您还可以将 DateTimeZone 传递给 DateTime() 构造函数以确保创建所需时区的日期,而不是服务器默认的日期。
回答by Vi8L
For first Date
第一次约会
$_firstDate = date("m-d-Y", strtotime($_yourDateString));
For New Date
对于新日期
$_newDate = date("Y-m-d",strtotime($_yourDateString));
回答by MAULIK MODI
If you have format dd-mm-yyyy then in PHP it won't work as expected. In PHP document they have below guideline.
如果您有 dd-mm-yyyy 格式,那么在 PHP 中它不会按预期工作。在 PHP 文档中,他们有以下指南。
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.
m/d/y 或 dmy 格式的日期通过查看各个组件之间的分隔符来消除歧义:如果分隔符是斜杠 (/),则假定为美国 m/d/y;而如果分隔符是破折号 (-) 或点 (.),则假定为欧洲 dmy 格式。
So, you just can't use as you wish. When your try to use dd/mm/yyyy format with this then it will remove FALSE. You can tweak with the following.
所以,你只是不能随心所欲地使用。当您尝试使用 dd/mm/yyyy 格式时,它将删除 FALSE。您可以使用以下方法进行调整。
$date = "23/02/2013";
$timestamp = strtotime($date);
if ($timestamp === FALSE) {
$timestamp = strtotime(str_replace('/', '-', $date));
}
echo $timestamp; // prints 1361577600
回答by Newton Singh
Like we have date "07/May/2018" and we need date "2018-05-07" as mysql compatible
就像我们有日期“07/May/2018”,我们需要日期“2018-05-07”作为mysql兼容
if (!empty($date)) {
$timestamp = strtotime($date);
if ($timestamp === FALSE) {
$timestamp = strtotime(str_replace('/', '-', $date));
}
$date = date('Y-m-d', $timestamp);
}
It works for me. enjoy :)
这个对我有用。请享用 :)
回答by Sodj
Since no one mentioned this, here's another way:
由于没有人提到这一点,这是另一种方式:
$date = date_create_from_format("m-d-Y", "10-16-2003")->format("Y-m-d");
$date = date_create_from_format("m-d-Y", "10-16-2003")->format("Y-m-d");
回答by Tim Morton
If you wish to accept dates using American ordering (month, date, year) for European style formats (using dash or period as day, month, year) while still accepting other formats, you can extend the DateTime class:
如果您希望接受使用美国排序(月、日、年)的欧式格式(使用破折号或句点作为日、月、年)的日期,同时仍接受其他格式,您可以扩展 DateTime 类:
/**
* Quietly convert European format to American format
*
* Accepts m-d-Y, m-d-y, m.d.Y, m.d.y, Y-m-d, Y.m.d
* as well as all other built-in formats
*
*/
class CustomDateTime extends DateTime
{
public function __construct(string $time="now", DateTimeZone $timezone = null)
{
// convert m-d-y or m.d.y to m/d/y to avoid PHP parsing as d-m-Y (substr avoids microtime error)
$time = str_replace(['-','.'], '/', substr($time, 0, 10)) . substr($time, 10 );
parent::__construct($time, $timezone);
}
}
// usage:
$date = new CustomDateTime('7-24-2019');
print $date->format('Y-m-d');
// => '2019-07-24'
Or, you can make a function to accept m-d-Y and output Y-m-d:
或者,您可以创建一个函数来接受 mdY 并输出 Ymd:
/**
* Accept dates in various m, d, y formats and return as Y-m-d
*
* Changes PHP's default behaviour for dates with dashes or dots.
* Accepts:
* m-d-y, m-d-Y, Y-m-d,
* m.d.y, m.d.Y, Y.m.d,
* m/d/y, m/d/Y, Y/m/d,
* ... and all other formats natively supported
*
* Unsupported formats or invalid dates will generate an Exception
*
* @see https://www.php.net/manual/en/datetime.formats.date.php PHP formats supported
* @param string $d various representations of date
* @return string Y-m-d or '----' for null or blank
*/
function asYmd($d) {
if(is_null($d) || $d=='') { return '----'; }
// convert m-d-y or m.d.y to m/d/y to avoid PHP parsing as d-m-Y
$d = str_replace(['-','.'], '/', $d);
return (new DateTime($d))->format('Y-m-d');
}
// usage:
<?= asYmd('7-24-2019') ?>
// or
<?php echo asYmd('7-24-2019'); ?>
回答by Azouz Mohamadi
to create date from any string use:
$date = DateTime::createFromFormat('d-m-y H:i', '01-01-01 01:00');
echo $date->format('Y-m-d H:i');
从任何字符串创建日期使用:
$date = DateTime::createFromFormat('dmy H:i', '01-01-01 01:00'); echo $date->format('Ymd H:i');