简体   繁体   中英

Extra space being added to array

My XML web service is sending an extra space in a datetime parameter of an array. Prior to April 1, the format was coming over as:

Sun Mar 31 02:05:49 2012 GMT

...but as of April 1, it was being reformatted as:

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

The problem is I'm exploding my array with a blankspace ( " " ) to take the [Month]+[Date]+[Year] but now I'm getting [Month]+[blank]+[Timestamp] .

Is there an array function to count backwards so I get [timezone] [year] [timestamp] [date] etc.?

Thanks.

You can split using regular expression

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

This will use one or more whitespaces as separator

为什么不只在整个字符串上使用strtotime()

If you want to parse a date, use 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

It also ensures that the time is converted to your current timezone, which you can change like this:

date_default_timezone_set('GMT');

Another alternative is to simply use strptime , which actually has been created to parse dates , but do not take timezones in consideration:

$parsed = strptime($time, '%c');

As Alex Howansky suggests, you should use some date/time parsing function. You can then use date() or DateTime::format() to output the date in your desired format:

$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 ) )
);

Output:

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"

You can use array_filter() to strip out all array entries that evaluate to FALSE. See: http://php.net/manual/en/function.array-filter.php

Although, I should note, I would probably use Darhazer's solution, myself. Just mentioning array_filter() here, as I'm not sure what the performance overhead of using preg_split() is in comparison to array_filter() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM