php Strtotime() 不适用于 dd/mm/YYYY 格式

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

Strtotime() doesn't work with dd/mm/YYYY format

php

提问by Simon

I really like the strtotime()function, but the user manual doesn't give a complete description of the supported date formats. strtotime('dd/mm/YYYY')doesn't work, it works only with mm/dd/YYYYformat.

我真的很喜欢这个strtotime()功能,但用户手册没有给出支持的日期格式的完整描述。strtotime('dd/mm/YYYY')不起作用,它仅适用于mm/dd/YYYY格式。

If I have date in dd/mm/YYYYformat, how can I convert it to YYYY-mm-dd? I can do it by using explode()function, but I think there are better solutions.

如果我有dd/mm/YYYY格式的日期,我该如何将其转换为YYYY-mm-dd?我可以通过使用explode()功能来做到这一点,但我认为有更好的解决方案。

回答by

Here is the simplified solution:

这是简化的解决方案:

$date = '25/05/2010';
$date = str_replace('/', '-', $date);
echo date('Y-m-d', strtotime($date));

Result:

结果:

2010-05-25

The strtotimedocumentationreads:

strtotime文件内容如下:

Dates in the m/d/yor d-m-yformats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/yis assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-yformat is assumed.

m/d/ydmy格式的日期通过查看各个组件之间的分隔符来消除歧义:如果分隔符是斜杠 ( /),则假定为美国m/d/y;而如果分隔符是破折号 ( -) 或点 ( .),则假定为欧洲dmy格式。

回答by salathe

You can parse dates from a custom format (as of PHP 5.3) with DateTime::createFromFormat

您可以使用DateTime::createFromFormat从自定义格式(从 PHP 5.3 开始)解析日期

$timestamp = DateTime::createFromFormat('!d/m/Y', '23/05/2010')->getTimestamp();

(Aside: The !is used to reset non-specified values to the Unix timestamp, ie. the time will be midnight.)

(旁白:!用于将非指定值重置为 Unix 时间戳,即时间将是午夜。)



If you do not want to (or cannot) use PHP 5.3, then a full list of available date/time formats which strtotime accepts is listed on the Date Formatsmanual page. That page more thoroughly describes the fact that m/d/Yis inferred over d/m/Y(but you can, as mentioned in the answers here, use d-m-Y, d.m.Yor d\tm\tY).

如果您不想(或不能)使用 PHP 5.3,那么 strtotime 接受的可用日期/时间格式的完整列表列在日期格式手册页上。该网页更彻底地描述了这样的事实m/d/Y推断过d/m/Y(但你可以像在答案中提到这里,使用d-m-Yd.m.Yd\tm\tY)。



In the past, I've also resorted to the quicky str_replacementioned in another answer, as well as self-parsing the date string into another format like

过去,我还使用了str_replace另一个答案中提到的 quicky ,以及将日期字符串自解析为另一种格式,例如

$subject   = '23/05/2010';
$formatted = vsprintf('%3d/%2d/%1d', sscanf($subject,'%02d/%02d/%04d'));
$timestamp = strtotime($formatted);

回答by Jonathan Roy

This is a good solution to many problems:

这是许多问题的一个很好的解决方案:

function datetotime ($date, $format = 'YYYY-MM-DD') {

    if ($format == 'YYYY-MM-DD') list($year, $month, $day) = explode('-', $date);
    if ($format == 'YYYY/MM/DD') list($year, $month, $day) = explode('/', $date);
    if ($format == 'YYYY.MM.DD') list($year, $month, $day) = explode('.', $date);

    if ($format == 'DD-MM-YYYY') list($day, $month, $year) = explode('-', $date);
    if ($format == 'DD/MM/YYYY') list($day, $month, $year) = explode('/', $date);
    if ($format == 'DD.MM.YYYY') list($day, $month, $year) = explode('.', $date);

    if ($format == 'MM-DD-YYYY') list($month, $day, $year) = explode('-', $date);
    if ($format == 'MM/DD/YYYY') list($month, $day, $year) = explode('/', $date);
    if ($format == 'MM.DD.YYYY') list($month, $day, $year) = explode('.', $date);

    return mktime(0, 0, 0, $month, $day, $year);

}

回答by L. Smit

From the STRTOTIME writeup Note:

来自 STRTOTIME 的文章注:

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 格式。

It is as simple as that.

它是如此简单。

回答by skullnobrains

fastest should probably be

最快的应该是

false!== ($date !== $date=preg_replace(';[0-2]{2}/[0-2]{2}/[0-2]{2};','--',$date))

this will return false if the format does not look like the proper one, but it wont-check wether the date is valid

如果格式看起来不正确,这将返回 false,但它不会检查日期是否有效

回答by alex

I haven't found a better solution. You can use explode(), preg_match_all(), etc.

我还没有找到更好的解决方案。您可以使用explode()preg_match_all()等等。

I have a static helper function like this

我有一个像这样的静态辅助函数

class Date {

    public static function ausStrToTime($str) {
        $dateTokens = explode('/', $str);
        return strtotime($dateTokens[1] . '/' . $dateTokens[0] . '/' . $dateTokens[2]); 

    }

}

There is probably a better name for that, but I use ausStrToTime()because it works with Australian dates (which I often deal with, being an Australian). A better name would probably be the standardised name, but I'm not sure what that is.

可能有一个更好的名字,但我使用ausStrToTime()它是因为它适用于澳大利亚日期(我经常处理,作为澳大利亚人)。更好的名称可能是标准化名称,但我不确定那是什么。

回答by smakintel.com

I tried to convert ddmmyy format to date("Y-m-d"format but was not working when I directly pass ddmmyy =date('dmy')

我试图将 ddmmyy 格式转换为date("Y-m-d"格式,但是当我直接通过时不起作用ddmmyy =date('dmy')

then realized it has to be in yyyy-mm-dd format so. used substring to organize

然后意识到它必须是 yyyy-mm-dd 格式。使用子串来组织

$strParam = '20'.substr($_GET['date'], 4, 2).'-'.substr($_GET['date'], 2, 2).'-'.substr($_GET['date'], 0, 2);  

then passed to date("Y-m-d",strtotime($strParam));

然后传递给 date("Y-m-d",strtotime($strParam));

it worked!

有效!

回答by Fi Horan

$srchDate = date_format(date_create_from_format('d/m/Y', $srchDate), 'Y/m/d');

$srchDate = date_format(date_create_from_format('d/m/Y', $srchDate), 'Y/m/d');

This will work for you. You convert the String into a custom date format where you can specify to PHP what the original format of the String is that had been given to it. Now that it is a date format, you can convert it to PHP's default date format, which is the same that is used by MySQL.

这对你有用。您可以将字符串转换为自定义日期格式,您可以在其中向 PHP 指定已提供给它的字符串的原始格式。既然是日期格式,就可以把它转换成PHP默认的日期格式,和MySQL使用的一样。

回答by user2623027

This workaround is simpler and more elegant than explode:

这种解决方法比爆炸更简单、更优雅:

$my_date = str_replace("/", ".", $my_date);
$my_date = strtotime($my_date);
$my_date = date("Y-m-d", $my_date);

You don't have to know what format you're getting the date in, but if it comes with slashes they are replaced with full stops and it is treated as European by strtotime.

您不必知道获取日期的格式,但如果它带有斜杠,它们将被替换为句号,并且 strtotime 将其视为欧洲格式。

回答by Joseph Mastey

Are you getting this value from a database? If so, consider formatting it in the database (use date_formatin mysql, for example). If not, exploding the value may be the best bet, since strtotime just doesn't seem to appreciate dd/mm/yyyy values.

您是否从数据库中获取此值?如果是这样,请考虑在数据库中对其进行格式化(date_format例如在 mysql 中使用)。如果不是,则爆炸该值可能是最好的选择,因为 strtotime 似乎并不欣赏 dd/mm/yyyy 值。