Now blogging at diego's weblog. See you over there!

outputting dates in RFC822 and ISO8601 formats


Okay, this is something else that is simple but generally requires to look at specs just to see how to do it properly. And these days, what with everyone generating RSS and such, creating properly formatted RFC822 and ISO 8601 dates is important to make sure the feeds validate. So here's the code, using Java's SimpleDateFormat, to output both formats properly.


import java.util.Date;
import java.text.SimpleDateFormat;

//... class definition here...

public static SimpleDateFormat ISO8601FORMAT
    = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
public static SimpleDateFormat RFC822DATEFORMAT
    = new SimpleDateFormat("EEE', 'dd' 'MMM' 'yyyy' 'HH:mm:ss' 'Z", Locale.US);

public static String getDateAsRFC822String(Date date)
{
  return RFC822DATEFORMAT.format(date);
}

public static String getDateAsISO8601String(Date date)
{
  String result = ISO8601FORMAT.format(date);
  //convert YYYYMMDDTHH:mm:ss+HH00 into YYYYMMDDTHH:mm:ss+HH:00
  //- note the added colon for the Timezone
  result = result.substring(0, result.length()-2)
    + ":" + result.substring(result.length()-2);
  return result;
}


Later: Aside from some fixes due to comments (thanks!), Erik, via IM, notes that RFC 822 has been superseded by RFC 2822, in which years on dates use four digits rather than two. The RSS Spec actually encourages the use of four digits from RFC 2822 (even though it explicitly mentions RFC 822 only). So I modified the code for that.

Also, Zoe, via email, notes that a cleaner way of generating ISO 8601 dates is to use the UTC designator "Z", which has the added advantage of making dates easier to parse back in Java. Clearly this is a better solucion when possible, however, this means that all times have to be changed into UTC, something that might not be desirable in many cases where you want to maintain Timezone information. The parsing of an ISO 8601 date with the colon is similarly "dirty" by having to remove the ":" by hand before being able to parse it from Java.

Categories: soft.dev
Posted by diego on January 4 2005 at 2:26 PM

Copyright © Diego Doval 2002-2011.
Powered by
Movable Type 4.37