Date Conversion from ISO 8601 To RFC 2822 format

Coding Critique is the place to post source code for peer review by other members of DevNetwork. Any kind of code can be posted. Code posted does not have to be limited to PHP. All members are invited to contribute constructive criticism with the goal of improving the code. Posted code should include some background information about it and what areas you specifically would like help with.

Popular code excerpts may be moved to "Code Snippets" by the moderators.

Moderator: General Moderators

Post Reply
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Date Conversion from ISO 8601 To RFC 2822 format

Post by Ambush Commander »

Extremely long function name. Quick and dirty.

Code: Select all

function convertDateFromISO8601ToRFC2822($date) {
        preg_match('/(\d+)-(\d+)-(\d+)T(\d+):(\d+):(\d+).(\d+)Z/',
            $date, $time_matches);
        list($x, $year, $month, $day, $hour, $minute, $second) =
            $time_matches;
        $timestamp = gmmktime($hour, $minute, $second, $month, $day, $year);
        return gmdate('r', $timestamp);
    }
This got me thinking: there must be a better way to do this! The function only accepts GMT style ISO 8601 dates. I am using this function to convert Subversion timestamps into RSS timestamps.
Example:

Code: Select all

echo convertDateFromISO8601ToRFC2822('1970-01-01T00:00:00Z');
Outputs: Thu, 01 Jan 1970 00:00:00 +0000
User avatar
aaronhall
DevNet Resident
Posts: 1040
Joined: Tue Aug 13, 2002 5:10 pm
Location: Back in Phoenix, missing the microbrews
Contact:

Post by aaronhall »

Does strtotime() not understand ISO8601? (I'm too lazy to check myself) -- if not, you could probably replace that "T" with a space and pass that along to strtotime.

Short of that, you could always spell out ISO and RFC in the function name :wink:
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Post by Ambush Commander »

It does.

:oops:

I swear, I tested it, and it didn't work! :-/ Oh well, makes my life easier.
User avatar
aaronhall
DevNet Resident
Posts: 1040
Joined: Tue Aug 13, 2002 5:10 pm
Location: Back in Phoenix, missing the microbrews
Contact:

Post by aaronhall »

:) PHP does that to me too
Post Reply