2015-05-05 136 views
2

我只是試圖分別提取日期的yearmonthday,以便我可以根據我的意願使用它。substr()未按預期工作

我將當前日期存儲在$today中,並使用substr()從中提取字符串。但是我正在從我正在做的事情中得到一些奇怪的行爲。

我當前的代碼:

$today = date("Y/m/d"); 

$_year = substr($today, 0,4); 
$_month = substr($today, 5,7); 
$_day = substr($today, 8, 10); 

echo $_year . " " . $_month; 

$_year工作正常預期,但問題從$_month出現的時候,無論在什麼位置我開始substr()的月份和日期被配對彼此。

任何人都可以幫我解決這個問題嗎?這讓我瘋狂。用斜線

只是explode()數據,然後使用list()將變量分配:

+0

請告訴我沒有輸出你得到? –

+0

$ _month = substr($ today,5,7);應該是$ _month = substr($ today,5,2);你想從位置5的2個字符,而不是7 – Grumpy

+0

@Grumpy javascript是罪魁禍首! ;) – Naveen

回答

5

你應該看看substr參考:http://php.net/manual/it/function.substr.php

那好玩ction接受3個參數:$length是要削減從$start

string substr (string $string , int $start [, int $length ]) 

在你的情況下開始的字符串的長度,這將正常工作:

$today = date("Y/m/d"); 
$_year = substr($today, 0,4); 
$_month = substr($today, 5,2); 
$_day = substr($today, 8, 2); 
echo $_year." ".$_month; 
+0

我在學習PHP之前學習了JavaScript,所以我犯了這個愚蠢的錯誤!感謝隊友 – Naveen

5

這應該爲你工作。

list($year, $month, $day) = explode("/", $today); 
+0

謝謝你隊友! – Naveen

+0

@DisortedCasanøva不客氣! – Rizier123

5

只需使用:

echo date("Y m"); 

如果你想在一個單獨的可變日期的每一個部分,我強烈建議您使用DateTime類:

$dt = new DateTime(); 
$year = $dt->format('Y'); 
$month = $dt->format('m'); 
$day = $dt->format('d'); 

echo $dt->format('Y m'); 
+0

您是否因爲字符限制而不得不在這裏放點?! – Rizier123

+0

增加了一些更有意義的東西... – hek2mgl

+0

對於你認爲有什麼字符限制?因爲獨角獸(開玩笑:)? (^現在看到你甚至有更好的OP。) – Rizier123

1
$today = date("Y/m/d"); 
$_year = substr($today, 0,4); 
$_month = substr($today, 5,7); 
$_day = substr($today, 8, 10); 
echo $_year." ".$_month; 

應該

$today = date("Y/m/d"); 
$_year = substr($today, 0,4); 
$_month = substr($today, 5,2); 
$_day = substr($today, 8, 2); 
echo $_year." ".$_month; 
1

substr()不像你想的那樣工作
你在想的: string substr (string $string , int $start , int $end)
但它是: string substr (string $string , int $start , [int $length)

所以使用substr($today,5,2)爲一個月,substr($today,7,2)白天

+0

好吧,我來自JavaScript,所以我發現它的罪魁禍首!謝啦! – Naveen

+0

沒問題,我知道那感覺:) – tektiv

1

你可以使用它作爲

$today = date("Y/m/d"); 
$today = explode("/", $today); 
$year = $today[0]; 
$month = $today[1]; 
$day = $today[2]; 
echo $year . ' ' . $month .' '. $day; // 2015 05 05 
+0

謝謝你隊友! – Naveen

+0

很高興幫助.. @DisortedCasanøva –