Reputation: 432
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.
Upvotes: 0
Views: 125
Reputation: 67705
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');
Upvotes: 1
Reputation: 29932
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"
Upvotes: 1
Reputation: 9875
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()
.
Upvotes: 0
Reputation: 26699
You can split using regular expression
$array = preg_split('/[\s]+/', $date);
This will use one or more whitespaces as separator
Upvotes: 1