Java Parse Date parseDate(String dateAsString)

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

Description

Parses the date.

License

Apache License

Parameter

Parameter Description
dateAsString the date as string

Exception

Parameter Description
ParseException the parse exception

Return

the date

Declaration

public static Date parseDate(String dateAsString) throws ParseException 

Method Source Code

//package com.java2s;
/*/*from w  ww .j  a  va2  s . c o  m*/
 * Copyright 2012 - 2016 Manuel Laggner
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

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

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    /**
     * Parses the date.
     * 
     * @param dateAsString
     *          the date as string
     * @return the date
     * @throws ParseException
     *           the parse exception
     */
    public static Date parseDate(String dateAsString) throws ParseException {
        Date date = null;

        Pattern datePattern = Pattern
                .compile("([0-9]{2})[_\\.-]([0-9]{2})[_\\.-]([0-9]{4})");
        Matcher m = datePattern.matcher(dateAsString);
        if (m.find()) {
            date = new SimpleDateFormat("dd-MM-yyyy").parse(m.group(1)
                    + "-" + m.group(2) + "-" + m.group(3));
        } else {
            datePattern = Pattern
                    .compile("([0-9]{4})[_\\.-]([0-9]{2})[_\\.-]([0-9]{2})");
            m = datePattern.matcher(dateAsString);
            if (m.find()) {
                date = new SimpleDateFormat("yyyy-MM-dd").parse(m.group(1)
                        + "-" + m.group(2) + "-" + m.group(3));
            }
        }

        if (date == null) {
            throw new ParseException("could not parse date from: \""
                    + dateAsString + "\"", 0);
        }

        return date;
    }
}

Related

  1. parseDate(String date, String format)
  2. parseDate(String date, String pattern)
  3. parseDate(String date, String pattern)
  4. parseDate(String date, String pattern)
  5. parseDate(String date, String pattern, TimeZone zone)
  6. parseDate(String dateAsString)
  7. parseDate(String dateFormat, String value)
  8. parseDate(String dateOfString, String targetFormat)
  9. parseDate(String datestr)