Java Parse Date parseDate(String str)

Here you can find the source of parseDate(String str)

Description

Parse the date from a string and return it.

License

Open Source License

Return

an initialized object or null if it can't parse the date. (It does not throw ParseException)

Declaration


static public Date parseDate(String str) 

Method Source Code


//package com.java2s;
/* The DateUtil utility provides several workhorse methods that
 * use Java's formatters to parse and format dates, times, etc.
 *
 * <!-- ====================== distribution terms ===================== -->
 * <p><blockquote//  w  w w .  ja v a 2s  .c  o  m
 *    style="border-style: solid; border-width:thin; padding: 1em 1em 1em 1em;">
 * <center>
 *          Copyright &copy; 2003, Allen I. Holub. All rights reserved.
 * </center>
 * <br>
 * <br>
 *       This code is distributed under the terms of the
 *       <a href="http://www.gnu.org/licenses/gpl.html"
 *       >GNU Public License</a> (GPL)
 *       with the following ammendment to section 2.c:
 *       <p>
 *       As a requirement for distributing this code, your splash screen,
 *       about box, or equivalent must include an my name, copyright,
 *       <em>and URL</em>. An acceptable message would be:
 * <center>
 *       This program contains Allen Holub's <em>XXX</em> utility.<br>
 *             (c) 2003 Allen I. Holub. All Rights Reserved.<br>
 *                   http://www.holub.com<br>
 * </center>
 *       If your progam does not run interactively, then the foregoing
 *       notice must appear in your documentation.
 * </blockquote>
 * <!-- =============================================================== -->
 * @author Allen I. Holub
 */

import java.text.*;
import java.util.*;
import java.util.regex.*;

public class Main {
    private static final Pattern noYear = Pattern.compile("\\s*[0-9]+\\/[0-9]+$");
    private static final Pattern dayFirst = Pattern.compile("([0-9]+)\\s+([A-Za-z]+)");
    private static final String thisYear = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));

    /** Parse the date from a string and return it. This method tries
     *  all the formats supported by {@link DateFormat} (FULL, LONG,
     *  MEDIUM, and SHORT in that order). It also recognises a few
     * formats not handled by the <code>DateFormat</code> class.
     *  <p> In an attempt to make date entry a bit more user friendly,
     * In particular, the following are recognized correctly:
     * <table border=1 cellspacing=0 cellpadding=1>
     * <tr><td> Input </td><td> Recognized as if they were: </td></tr>
        
     * </table>
     *
     *  @return an initialized {@link java.util.Date} object or
     *              <code>null</code> if it can't parse the date.
     *              (It does not throw <code>ParseException</code>)
     */

    static public Date parseDate(String str) { // assert str != null;

        if (str.length() == 0)
            return null;

        str = str.replace('-', '/'); // just in case.

        Matcher m = dayFirst.matcher(str); // 1 Jan instead of Jan 1
        if (m.find()) {
            str = m.replaceFirst(m.group(2) + " " + m.group(1));
        }

        m = noYear.matcher(str); // add a year to 10/15 format.
        if (m.find())
            str += ("/" + thisYear);

        Date parsed = tryToParse(str);
        if (parsed == null)
            parsed = tryToParse(str + ", " + thisYear); // try adding a year
        return parsed;
    }

    static private Date tryToParse(String str) {
        Date date = null;

        try {
            DateFormat formatter = DateFormat.getDateInstance(DateFormat.FULL);
            formatter.setLenient(true);
            date = formatter.parse(str);
        } catch (ParseException pel) {
            try {
                DateFormat formatter = DateFormat.getDateInstance(DateFormat.LONG);
                formatter.setLenient(true);
                date = formatter.parse(str);
            } catch (ParseException pe2) {
                try {
                    DateFormat formatter = DateFormat.getDateInstance(DateFormat.MEDIUM);
                    formatter.setLenient(true);
                    date = formatter.parse(str);
                } catch (ParseException pe3) {
                    try {
                        DateFormat formatter = DateFormat.getDateInstance(DateFormat.SHORT);
                        formatter.setLenient(true);
                        date = formatter.parse(str);
                    } catch (ParseException pe4) {
                        return null;
                    }
                }
            }
        }

        return date;
    }
}

Related

  1. parseDate(String str)
  2. parseDate(String str)
  3. parseDate(String str)
  4. parseDate(String str)
  5. parseDate(String str)
  6. parseDate(String str, boolean strict, String... parsePatterns)
  7. parseDate(String str, DateFormat df)
  8. parseDate(String str, Locale locale, String... parsePatterns)
  9. parseDate(String str, String pattern)