RFC 2822 date-time string contains timezone offset e.g. the given string Sat, 13 Mar 2010 11:29:05 -0800 has a timezone offset of -08:00 hours from UTC i.e. the equivalent date-time at UTC can be obtained by adding 8 hours to Sat, 13 Mar 2010 11:29:05.
java.time
The modern date-time API API has OffsetDateTime
to represent a date-time with timezone offset.
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
class Main {
public static void main(String[] args) {
String strRFC2822DateTimeStr = "Sat, 13 Mar 2010 11:29:05 -0800";
OffsetDateTime odt = OffsetDateTime.parse(strRFC2822DateTimeStr, DateTimeFormatter.RFC_1123_DATE_TIME);
System.out.println(odt);
// Alternatively: using a custom DateTimeFormatter
DateTimeFormatter parser = DateTimeFormatter.ofPattern("EEE, dd MMM uuuu HH:mm:ss XX", Locale.ENGLISH);
System.out.println(OffsetDateTime.parse(strRFC2822DateTimeStr, parser));
// In case you need the equivalent date-time at UTC
OffsetDateTime odtUtc = odt.withOffsetSameInstant(ZoneOffset.UTC);
System.out.println(odtUtc);
}
}
Output:
2010-03-13T11:29:05-08:00
2010-03-13T11:29:05-08:00
2010-03-13T19:29:05Z
Learn more about the modern Date-Time API from Trail: Date Time.
Some useful links:
- Never use SimpleDateFormat or DateTimeFormatter without a Locale.
- You can use
y
instead of u
but I prefer u
to y
.
- How to use
OffsetDateTime
with JDBC.