Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

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

import java.util.Locale;

public class Main {
    /**
     * Date formats used for Date parsing.
     */
    static final SimpleDateFormat FORMATS[] = { new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US),
            new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US),
            new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sss'Z'", Locale.US),
            new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US),
            new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US),
            new SimpleDateFormat("EEEEEE, dd-MMM-yy HH:mm:ss zzz", Locale.US),
            new SimpleDateFormat("EEE MMMM d HH:mm:ss yyyy", Locale.US) };

    /**
     * Loops over all the possible date formats and tries to find the right one.
     *
     * @param dateValue
     *            to parse
     * @return a valid {@link Date} or null if none of the formats matched.
     */
    public static Date parseDate(String dateValue) {
        if (dateValue == null)
            return null;

        Date date = null;
        for (final SimpleDateFormat format : FORMATS) {
            try {
                final SimpleDateFormat clonedFormat = (SimpleDateFormat) format.clone();
                date = clonedFormat.parse(dateValue);
                break;
            } catch (ParseException e) {
                // We loop through this until we found a valid one.
                //noinspection UnnecessaryContinue
                continue;
            }
        }

        return date;
    }
}