将德语日期转换为Y-m-d是无效的


Converting a German date to Y-m-d does not work?

我有一个这样的日期:2。2012年2月

我想把它转换成2012-02-02,所以我写了这个代码:

$date = '2. Februar 2012';
$date = date('Y-m-d', $date);

$date变量要么为空,要么在1970-01-01之后为空,有什么错误或缺失?

注意:日期为德语格式,因此不是二月,而是二月。我用这种方式从日期选择器中获取日期。

谢谢!

您可以使用*strtotime,还需要在strtotime函数中传递有效的日期格式,因为$date变量没有有效的格式。

您的.和拼写错误的月份名称。在通过strtotime之前,你必须清除这些。我使用了str_replace

$date = '2. Februar 2012';
$date = date('Y-m-d', strtotime(str_replace('Februar','february',str_replace('.','', $date))));

这样使用:

$date = '2. February 2012';
$date = strtotime($date);
$date = date('Y-m-d', $date);
echo $date;

老问题,但iv'e构建了一个用于比较两个日期的解决方案(来自德国基地,如"9。2022年5月")动态转换为美国日期格式。

$post_date = get_field( "veranstaltung_datum", $veranstaltung->ID ); // e.g. "9. Mai 2022"
$post_date_month_de = preg_replace("/[^a-zA-Z]+/", "", $post_date); // isolate the month -> "Mai"
$post_date_month_en = replaceGermanMonth($post_date_month_de); // Switch replaces Month Name -> "May"
$post_date = date('Y-m-d', strtotime(str_replace($post_date_month_de, $post_date_month_en ,str_replace('.','', $post_date)))); // replace the "." and the "Mai" with "" and "May"
$post_date = strtotime($post_date); // convert in to ms since 01.01.1970
   
// get the current date in ms since 01.01.1970
$current_date = strtotime(date('Y-m-d'));
if ($current_date > $post_date) {
   // add the magic
}

这是我用来更改月份的开关:

function replaceGermanMonth($month) {
    switch ($month) {
    case 'Januar':
        return "January";
        break;
    case 'Februar':
        return "February";
        break;
    case "März":
        return "March";
        break;
    case "April":
        return "April";
        break;
    case "Mai":
        return "May";
        break;
    case "Juni":
        return "June";
        break;
    case "Juli":
        return "July";
        break;
    case "August":
        return "August";
        break;
    case "September":
        return "September";
        break;
    case "Oktober":
        return "October";
        break;
    case "November":
        return "November";
        break;
    case "Dezember":
        return "December";
        break;
    default:
        break;
    }
}
php中的

date()函数期望第一个参数为字符串。在你的例子中是可以的。Seconds参数是可选的,它应该是带有要转换的时间戳的整数

参考:http://php.net/manual/en/function.date.php

使用strtotime

putenv('LC_ALL=de_DE');
putenv('LANG=de'); 
setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'deu_deu');
$date = '2. Februar 2012';
$date = date('Y-m-d', strtotime($date));

使用strtotime()

strtotime("2 February 2012") will return the unix timestamps.
mktime(0, 0, 0, 2, 2, 2012) will return the same unix timestamps.

如果你能运行

$ts = mktime(0, 0, 0, 2, 2, 2012);
echo date("Y-m-d H:i:s", $ts); // output 2012-02-02 00:00:00  
You can run the following too
$ts = strtotime("2 February 2012");
echo date("Y-m-d H:i:s", $ts); // output 2012-02-02 00:00:00