Java Parse Date parseDate(String dateStr)

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

Description

parse Date

License

Apache License

Declaration

public static Date parseDate(String dateStr) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

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

import java.util.Date;
import java.util.regex.Pattern;

public class Main {
    private final static Pattern DATE_PATTERN = Pattern.compile("\\d\\d\\d\\d-\\d\\d?-\\d\\d?");
    private final static String DATE_FORMAT = "yyyy-MM-dd";

    public static Date parseDate(String dateStr) {
        try {/*  w  ww .  j a va  2  s.c o m*/
            if (isValidDateString(dateStr)) {
                return (new SimpleDateFormat(DATE_FORMAT).parse(dateStr));
            } else if (dateStr.indexOf("T") > 0) {
                return (new SimpleDateFormat(DATE_FORMAT).parse(dateStr.substring(0, dateStr.indexOf('T'))));
            } else {
                return (new SimpleDateFormat(DATE_FORMAT).parse(dateStr.substring(0, dateStr.indexOf(" "))));
            }

        } catch (ParseException e) {
            throw new IllegalArgumentException("Invalid date format: " + dateStr, e);
        }
    }

    public static boolean isValidDateString(String dateStr) {
        return dateStr == null ? false : DATE_PATTERN.matcher(dateStr).matches();
    }
}

Related

  1. parseDate(String dateStr)
  2. parseDate(String dateStr)
  3. parseDate(String dateStr)
  4. parseDate(String dateStr)
  5. parseDate(String dateStr)
  6. parseDate(String dateStr)
  7. parseDate(String datestr)
  8. parseDate(String dateStr, SimpleDateFormat... formats)
  9. parseDate(String dateStr, String dateFormat)