2012-09-25 150 views
1

我有这样的一段代码,让我从数据库中的字段:检索日期,月份,年份从日期在PHP

$end_date=$row1['end_date']; 

如果我打印出来它给了我喜欢的东西:25-09- 2012 我需要的是获取月份值,年份和日期。 类似:

$month=09; 
$day=25; 
$year=2012; 

我怎样才能做到这一点? 谢谢!

+0

看看strtodate和日期函数 – sachleen

+0

看看我的答案。 –

回答

2

在你的情况,你可以使用explode功能是这样的:

// store a string containing "25-09-2012" 
$end_date = $row1['end_date']; 

// split "25-09-2012" into an array of three elements 
$thedate = explode("-", $end_date); 

// retrieve the values 
$month = $thedate[0]; // 25 
$day = $thedate[1]; // 09 
$year = $thedate[2]; // 2012 
+0

非常感谢,很好,干净:) 我接受你的问题在几分钟内:) – Tao

+0

我可以问你一些事吗? 我需要这个数字我提取没有0,我的意思是如果月份是01,我需要它1,我该怎么做? – Tao

+0

您必须将字符串转换为整数,因为您可以简单地使用[intval](http://php.net/manual/en/function.intval.php)函数。 –

1

尝试 [month('end_date')] [day('end_date')] [year('end_date')]

或者使用explode和使用 - 作为分隔符

+0

在MySQL中,它适用于日期字段,它拉的月份,所以想知道它可能在这种情况下工作。如果没有建议使用爆炸 – RSM

1
$values = getdate(strtotime($row1['end_date'])); 
echo $values['mon']; //month 
echo $values['mday']; //day 
echo $values['year']; //year 
3

使用DateTime

$date = new DateTime($row1['end_date']); 
$year = $date -> format('Y'); 
$month = $date -> format('m'); 
$day = $date -> format('d'); 

如果时间戳都像一个规定,保持简单:

list($day, $month, $year) = explode('-', $row1['end_date']); 
1

答:您可以使用DateTime

$date = DateTime::createFromFormat('d-m-Y',$row1['end_date']); 
$month = $date->format("m"); 
$day = $date->format("d"); 
$year = $date->format("Y"); 

B.使用strtotime

$date = strtotime($row1['end_date']); 
$month = date("m", $date); 
$day = date("d", $date); 
$year = date("Y", $date); 

C.您可以通过串只是sscanf扫描

$date = sscanf($row1['end_date'], "%d-%d-%d"); 
$month = $date[0] ; 
$day = $date[1] ; 
$year = $date[2] ; 

D.另一种方法是使用list & explode

list($day, $month, $year) = explode('-', $row1['end_date']); 
1

只需一行,然后根据需要进行格式化即可。 (十二月,十二月,十二月)等以及日期()。

list($month, $day, $year) = explode('-', date('m-d-Y', strtotime($row1['end_date']))); 
相关问题