parse RFC822 Date String - Java java.util

Java examples for java.util:Date Format

Description

parse RFC822 Date String

Demo Code


//package com.java2s;
import java.text.DateFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class Main {
    private static final String[] RFC822_MASKS = {
            "EEE, dd MMM yyyy HH:mm:ss z", "EEE, dd MMM yyyy HH:mm:ss Z",
            "EEE, dd MMM yy HH:mm:ss z", "EEE, dd MMM yy HH:mm z",
            "dd MMM yy HH:mm:ss z", "dd MMM yy HH:mm z" };

    public static Date parseRFC822(String sDate, Locale locale) {
        int utIndex = sDate.indexOf(" UT");
        if (utIndex > -1) {
            String pre = sDate.substring(0, utIndex);
            String post = sDate.substring(utIndex + 3);
            sDate = pre + " GMT" + post;
        }//  w w w .j  a  v  a  2 s .  c  o m
        return parseUsingMask(RFC822_MASKS, sDate, locale);
    }

    private static Date parseUsingMask(String[] masks, String sDate,
            Locale locale) {
        if (sDate != null) {
            sDate = sDate.trim();
        }
        ParsePosition pp = null;
        Date d = null;
        for (int i = 0; (d == null) && (i < masks.length); i++) {
            DateFormat df = new SimpleDateFormat(masks[i], locale);

            df.setLenient(true);
            try {
                pp = new ParsePosition(0);
                d = df.parse(sDate, pp);
                if (pp.getIndex() != sDate.length()) {
                    d = null;
                }
            } catch (Exception localException) {
            }
        }
        return d;
    }
}

Related Tutorials