如何在php中将day添加到字符串中


How to add day to a string in php

我当前的日期格式为年月日。我需要将天数默认为我在php中的格式。

例如:

12/2009->07/12/2009

我试过这个代码:

$currdate = '07/'.$currdate;
$newFormat = date('d-M-Y',strtotime($currdate));

但新的格式是错误的,它于2009年7月12日输出。

-----------------编辑-------------------------

我尝试过**DateTime::createFromFormat**。因为我的$currdate日期格式只有月份和年份,所以不接受。我犯了一个致命的错误。

strtotime需要美国日期格式。使用datetime::createFromFormat代替:

$date = DateTime::createFromFormat('d/m/Y', $currdate);
echo $date->format('Y-m-d');

编辑以更好地解释:

当您使用带斜杠(/)的日期时,PHP strtotime会认为它是m/d/Y格式,这是美国的方式。如果使用破折号(-),它将采用d-m-Y格式。如果您使用点(.),它将采用Y.m.d格式。