2012-04-02 145 views
0

我的XML Web服務正在發送陣列的日期時間參數中的額外空間。此前4月1日,該格式是過來爲:額外空間被添加到陣列

Sun Mar 31 02:05:49 2012 GMT 

...但4月1日,它被重新格式化爲:

Sun Apr 1 02:05:49 2012 GMT (Note the extra space between "Apr" and "1") 

問題是我在我的爆炸陣列與空格(" ")採取[月] + [日期] + [年]但現在我得到[月] + [空白] + [時間戳]

是否有數組函數向後計數,所以我得到[時區] [年] [時間戳] [日期]等?

謝謝。

+0

可能相關的問題:未設置空白陣列上的飛行項目](http://stackoverflow.com/questions/2317362/unset-blank-array-items-on-the-fly) – Matthematics 2012-04-02 14:44:28

回答

1

您可以分割使用正則表達式

$array = preg_split('/[\s]+/', $date); 

這將使用一個或多個空格作爲分隔符

+0

謝謝達哈澤...讓我試試 – bobbiloo 2012-04-02 14:38:07

+0

這工作很好達爾..感謝 – bobbiloo 2012-04-02 14:49:03

1

爲什麼不直接使用strtotime()對整個字符串?

+0

不會那會降低性能? – Matthematics 2012-04-02 14:42:31

+0

感謝提示亞歷克斯,但我必須得到這個到MSFT友好的格式 – bobbiloo 2012-04-02 14:44:02

+0

@Lübnah:誰在乎,影響是如此之小,它並不意味着什麼。但是,它確保日期正確解析,與當前OP的方法不同。 – netcoder 2012-04-02 14:44:20

0

您可以使用array_filter()去除所有評估爲FALSE的數組條目。見:http://php.net/manual/en/function.array-filter.php

雖然,我應該注意到,我可能會使用達哈澤的解決方案,我自己。這裏只提到array_filter(),因爲我不確定使用preg_split()array_filter()相比的性能開銷是多少。

1

如果要分析日期,使用strtotime

$time = 'Sun Apr 1 02:05:49 2012 GMT'; 

$month = date('M', $ts); // Apr 
$day = date('j', $ts); // 1 
$year = date('Y', $ts); // 2012 

這也保證了時間轉換爲當前的時區,你可以改變這樣的:

date_default_timezone_set('GMT'); 

另一個替代方法是簡單地使用strptime,實際上已創建到解析日期,但不考慮時區:

​​3210
1

正如Alex Howansky所說,你應該使用一些日期/時間解析函數。然後,您可以在您需要的格式使用日期()或日期時間::格式()輸出日期:

$formatA = 'Sat Mar 31 02:05:49 2012 GMT'; 
$formatB = 'Sun Apr 1 02:05:49 2012 GMT'; 

var_dump(
    new DateTime($formatA), 
    new DateTime($formatB), 
    date('Y-m-d H:i:s', strtotime($formatA)), 
    date('Y-m-d H:i:s', strtotime($formatB)) 
); 

輸出:

object(DateTime)#1 (3) { 
    ["date"]=> 
     string(19) "2012-03-31 02:05:49" 
    ["timezone_type"]=> 
     int(2) 
    ["timezone"]=> 
     string(3) "GMT" 
} 

object(DateTime)#2 (3) { 
    ["date"]=> 
     string(19) "2012-04-01 02:05:49" 
    ["timezone_type"]=> 
     int(2) 
    ["timezone"]=> 
     string(3) "GMT" 
} 

string(19) "2012-03-31 04:05:49" 

string(19) "2012-04-01 04:05:49"