4

I'm getting some data from the Twilio API and one of the Date fields comes in this format

"Wed, 19 Nov 2014 00:41:08 +0000"

I've tried

Date.parse('Wed, 19 Nov 2014 00:41:08 +0000');

DateTime.parse('Wed, 19 Nov 2014 00:41:08 +0000');

also with valueOf and they all give me the same error message

Invalid format: "Wed, 19 Nov 2014 00:41:08 +0000"

Any ideas?

6

I'm not aware of any standard way to parse this, but here's a quick method to do it:

Map<String, String> months = new Map<String, String>
{
    'Jan' => '01',
    'Feb' => '02',
    'Mar' => '03',
    'Apr' => '04',
    'May' => '05',
    'Jun' => '06',
    'Jul' => '07',
    'Aug' => '08',
    'Sep' => '09',
    'Oct' => '10',
    'Nov' => '11',
    'Dec' => '12'    
};

public DateTime parseRFC2822(string input)
{
    List<string> parts = input.substring(input.indexOf(', ') + 2).split(' '), 
        dateparts = new List<String>{parts[2], parts[1],parts[0]},
        timeparts = parts[3].split(':');
    dateparts[1] = months.get(dateparts[1]);
    return DateTime.newInstanceGMT(integer.valueOf(dateParts[0]), 
                                   integer.valueOf(dateParts[1]),
                                   integer.valueOf(dateParts[2]),
                                   integer.valueOf(timeparts[0]),
                                   integer.valueOf(timeparts[1]),
                                   integer.valueOf(timeparts[2]));
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.