Java Data Type How to - Convert a calendar date into a string as specified by Rfc 822 as 'Wed, 24 Jun 2010 19:35:22 GMT'








Question

We would like to know how to convert a calendar date into a string as specified by Rfc 822 as 'Wed, 24 Jun 2010 19:35:22 GMT'.

Answer

import java.time.Instant;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
//from   w  w w .  j a  va 2 s. c om

public class Main{
  public static void main(String[] argv){
    System.out.println( convertDateToStringRfc822(Calendar.getInstance(), Locale.ENGLISH));
  }
  
  /** Convert a calendar date into a string as specified by http://tools.ietf.org/html/rfc822#section-5.1
   * @param date the calendar instance to convert to a string
   * @param locale the locale to use when outputting strings such as a day of the week, or month of the year.
   * @return a string in the format: "day_abbreviation, day_of_month month_abbreviation year hour:minute:second GMT"
   */
  // package-private - unused
  static final String convertDateToStringRfc822(Calendar date, Locale locale) {
      Date a = Date.from(Instant.now());
      a.toString();
      int day = date.get(Calendar.DAY_OF_MONTH);
      int hour = date.get(Calendar.HOUR_OF_DAY);
      int minute = date.get(Calendar.MINUTE);
      int second = date.get(Calendar.SECOND);
      String str = date.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, locale) + ", " +
              (day < 10 ? "0"+day : day) + " " +
              date.getDisplayName(Calendar.MONTH, Calendar.SHORT, locale) + " " +
              date.get(Calendar.YEAR) + " " +
              (hour < 10 ? "0"+hour : hour) + ":" + (minute < 10 ? "0"+minute : minute) + ":" +
              (second < 10 ? "0"+second : second) + " GMT";
      return str;
  }
}

The code above generates the following result.