2014-01-05 164 views
0

你好,請幫我把字符串轉換成日期: - 用Google搜索關於這一點,但沒有得到期望的結果轉換字符串到日期在PHP中的「年月日」

<?php 

$todaydate= $_GET['date']; //sending 201213 ie index.php?date=201213 

$todaydate=preg_replace("/[^0-9,.]/", "", $todaydate); 

echo $todaydate."----------"; //prints 201213 

$todaydate = date("ymd", strtotime($todaydate)); 

echo $todaydate."----------"; // i want to print 131220 here but it prints today's date 
?> 
+1

你似乎認爲'strtotime()'是某種神奇/全知/通靈,並且可以處理任何你投擲它的日期。它不是也不能......你需要爲它提供一個日期字符串它可以**處理,或者使用字符串操作+ mktime()來分割你的日期字符串。並且確切** ** 201213是什麼**? 2012年第13個月?第13天?如果** WE **不能告訴它是什麼,是什麼讓你認爲PHP可以弄清楚它? –

+1

你需要正確的日期輸入.SEE格式:http://www.php.net/manual/en/function.date.php –

+0

或任何方式將201213轉換爲131220! –

回答

1

嘗試mktime

<?php 
    $todaydate = $_GET['date']; //sending 201213 ie index.php?date=201213 
    $todaydate = preg_replace("/[^0-9,.]/", "", $todaydate); 
    echo $todaydate."----------"; //prints 201213 

    $d = substr($todaydate, 0, 2); 
    $m = substr($todaydate, 2, 2); 
    $y = substr($todaydate, 4, 2); 
    $t = mktime (0, 0, 0, $m, $d, $y); 

    $todaydate = date("ymd", $t); 
    echo $todaydate."----------"; // i want to print 131220 here but it prints today's date 
?> 
1

更簡單solutoin:

<?php 
     $todaydate = $_GET['date']; //sending 201213 ie index.php?date=201213 
     $todaydate = preg_replace("/[^0-9,.]/", "", $todaydate); 
     $date = DateTime::createFromFormat('dmy', $todaydate); 
     echo $date->format('ymd'); 
?> 

與此代碼,你可以使用ny格式顯示你的日期,因爲你現在有一個有效的日期。

相關問題