我在PHP中使用日期函数分别从日期获取日,月和年。我在这个函数中传递了两个日期,一个是fromdate,另一个是todate。在todate的情况下,函数返回适当的值,但在fromdate的情况下,函数分别返回月、日、年的0、1、2。
下面是我在PHP中使用的代码:
// here i am passing values for fromdate and todate fetched from POST, these values are proper
$from = $_POST['event_fromdate'];
$to=$_POST['event_todate'];
// here i am fetching month,day & year separately from fromdate , these values are not proper
$time['month'] = date('m',strtotime($from));
$time['day'] = date('d',strtotime($from));
$time['year'] = date('Y',strtotime($from));
// here i am fetching month,day & year separately from todate , these values are proper
$time1['month'] = date('m',strtotime($to));
$time1['day'] = date('d',strtotime($to));
$time1['year'] = date('Y',strtotime($to));
依次打印这些值,输出如下:
Actual From date: 13-APR-2013
Actual To date : 14-APR-2013
'From date' fetched from date function:
month = 0
day = 1
year = 2
'To date' fetched from date function:
month = 04
day = 14
year = 2013
在这里,我已经尝试了各种方式,但没有得到为什么我在FROM DATE的情况下得到不适当的结果。
如果你只是把它放在一个DateTime对象中,你可以从那里提取所有的值,节省你很多重复的代码。
$dt_to = new DateTime($to);
$some_info = array(
'day' => $dt_to->format('d'),
'month' => $dt_to->format('m'),
'year' => $dt_to->format('Y')
);
然而,将DateTime对象传递给实际需要日/月/年的端点将是一个更简洁的解决方案。