Java Parse Date parseDate(final String source)

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

Description

Parse the Date using pattern "yyyy-MM-dd"

License

Open Source License

Parameter

Parameter Description
source a parameter

Exception

Parameter Description

Declaration

public static Date parseDate(final String source) throws ParseException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.Date;

public class Main {
    public static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    public static final SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static final SimpleDateFormat monthFormat = new SimpleDateFormat("yyyy-MM");

    /**//w  w  w.  j  a  v  a  2s . c  o  m
     * Parse the Date using pattern "yyyy-MM-dd"
     *
     * @param source
     * @return
     * @throws java.text.ParseException
     */
    public static Date parseDate(final String source) throws ParseException {
        if (source == null || source.trim().length() == 0) {
            return null;
        }
        return dateFormat.parse(source);
    }

    public static Date parse(final String source) throws ParseException {
        if (source == null || source.trim().length() == 0) {
            return null;
        }
        if (source.length() <= dateTimeFormat.toPattern().length()
                && source.length() >= dateTimeFormat.toPattern().length() - 5) {
            try {
                return dateTimeFormat.parse(source);
            } catch (ParseException ex) {
            }
        }
        if (source.length() <= dateFormat.toPattern().length()
                && source.length() >= dateFormat.toPattern().length() - 2) {
            try {
                return dateFormat.parse(source);
            } catch (ParseException ex) {
            }
        }
        if (source.length() <= monthFormat.toPattern().length()
                && source.length() >= monthFormat.toPattern().length() - 1) {
            try {
                return monthFormat.parse(source);
            } catch (ParseException ex) {
            }
        }
        return dateTimeFormat.parse(source);
    }
}

Related

  1. parseDate(final String date, final String format)
  2. parseDate(final String dateStr)
  3. parseDate(final String dateString)
  4. parseDate(final String pDate)
  5. parseDate(final String revision)
  6. parseDate(final String source)
  7. parseDate(final String str)
  8. parseDate(final String str, final Locale locale, final String... parsePatterns)
  9. parseDate(final String value)