1

I have an HttpResponse object with the Date as a header property. Its format looks like this:

Thu, 13 Jul 2017 06:59:43 GMT

and I would like to parse it as an Apex Datetime object.

I did multiple tries:

Datetime after = Datetime.parse('Thu, 13 Jul 2017 06:59:43 GMT'); 
//Not able to parse

Datetime after = (Datetime) JSON.deserialize(
            '"' + 'Thu, 13 Jul 2017 06:59:43 GMT' + '"',
            Datetime.Class
); 
//Not a JSON valid ISO 8601 Datetime

My last hope is a manual parsing but I would like to avoid it at first. Any idea ?

2 Answers 2

1

No, it is not possible to parse this datetime string without parse datetime as string. To parse it use the following snippet:

Map<String, Integer> shortMonthNames = new Map<String, Integer>();
for(Integer i=1; i <=12; i++){
    shortMonthNames.put(DateTime.newInstanceGmt(1970, i, 1).format('MMM'), i);
}
List<String> splitParts = 'Thu, 13 Jul 2017 06:59:43 GMT'.split(', | ');
List<String> timeParts = splitParts[4].split(':');
DateTime after = DateTime.newInstanceGmt(
    Integer.valueOf(splitParts[3]),
    shortMonthNames.get(splitParts[2]),
    Integer.valueOf(splitParts[1]),
    Integer.valueOf(timeParts[0]),
    Integer.valueOf(timeParts[1]),
    Integer.valueOf(timeParts[2])
    );
System.debug(after);

DEBUG|2017-07-13 06:59:43

0

I use regex instead of split

Map<String, String> months = new Map<String, String> {
  'Jan' => '1',
  'Feb' => '2',
  'Mar' => '3',
  'Apr' => '4',
  'May' => '5',
  'Jun' => '6',
  'Jul' => '7',
  'Aug' => '8',
  'Sep' => '9',
  'Oct' => '10',
  'Nov' => '11',
  'Dec' => '12'
};

String responseDate = resp.getHeader('Date');
Pattern p = Pattern.compile('^.{4}\\s(\\d+)\\s(\\S+)\\s(\\d{4})\\s(.{8})\\sGMT');
Matcher m = p.matcher(responseDate);

if(m.groupCount() == 4) {
  String jsonDate = String.format('{0}-{1}-{2}\'T\'{3}', new String[] {
    m.group(3), months.get(m.group(2)), m.group(1), m.group(4)
  });
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .