Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing RFC 2822 date in JAVA

Tags:

I need to parse an RFC 2822 string representation of a date in Java. An example string is here:

Sat, 13 Mar 2010 11:29:05 -0800

It looks pretty nasty so I wanted to make sure I was doing everything right and would run into weird problems later with the date being interpreted wrong either through AM-PM/Military time problems, UTC time problems, problems I don't anticipate, etc...

Thanks!

like image 876
Chris Dutrow Avatar asked Mar 16 '10 22:03

Chris Dutrow


People also ask

How parse DD MMM YYYY in Java?

For parsing a String to Date we need an instance of the SimpleDateFormat class and a string pattern as input for the constructor of the class. String pattern = "MM-dd-yyyy"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); Date date = simpleDateFormat. parse("12-01-2018"); System.

How do you check if the Date is in YYYY MM DD format in Java?

DateValidator validator = new DateValidatorUsingDateFormat("MM/dd/yyyy"); assertTrue(validator. isValid("02/28/2019")); assertFalse(validator. isValid("02/30/2019"));

What is DateFormat in Java?

DateFormat is an abstract class for date/time formatting subclasses which formats and parses dates or time in a language-independent manner. The date/time formatting subclass, such as SimpleDateFormat , allows for formatting (i.e., date -> text), parsing (text -> date), and normalization.


2 Answers

This is quick code that does what you ask (using SimpleDateFormat)

String rfcDate = "Sat, 13 Mar 2010 11:29:05 -0800";
String pattern = "EEE, dd MMM yyyy HH:mm:ss Z";
SimpleDateFormat format = new SimpleDateFormat(pattern);
Date javaDate = format.parse(rfcDate);

//Done.

PS. I've not dealt with exceptions and concurrency here (as SimpleDateFormat is not synchronized when parsing date).

like image 79
Buhake Sindi Avatar answered Sep 28 '22 09:09

Buhake Sindi


If your application is using another language than English, you may want to force the locale for the date parsing/formatting by using an alternate SimpleDateFormat constructor:

String pattern = "EEE, dd MMM yyyy HH:mm:ss Z";
SimpleDateFormat format = new SimpleDateFormat(pattern, Locale.ENGLISH);
like image 21
Laurent VB Avatar answered Sep 28 '22 10:09

Laurent VB