Java Date Parse dateFromString(String s)

Here you can find the source of dateFromString(String s)

Description

Get a date from a String.

License

Open Source License

Parameter

Parameter Description
s The date as a String.

Return

The date.

Declaration

public static Date dateFromString(String s) 

Method Source Code

//package com.java2s;
/*// w  ww.  ja  v  a 2 s  . c  o m
 * (C) Copyright 2014 Fabien Barbero.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl-2.1.html
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 */

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

public class Main {
    private static final String DATE_REGEX = "^[0-9]{4}-[0-9]{2}-[0-9]{2}$";
    private static final DateFormat DATE_FORMAT = DateFormat.getDateInstance();
    private static final String DATE_TIME_REGEX = "^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$";
    private static final DateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * Get a date from a String.
     *
     * @param s The date as a String.
     * @return The date.
     */
    public static Date dateFromString(String s) {
        if (s == null) {
            return null;
        }
        try {
            if (s.matches(DATE_REGEX)) {
                return DATE_FORMAT.parse(s);

            } else if (s.matches(DATE_TIME_REGEX)) {
                return DATE_TIME_FORMAT.parse(s);

            } else {
                long date = Long.parseLong(s);
                return new Date(date * 1000);
            }

        } catch (ParseException ex) {
            throw new UnsupportedOperationException("Error parsing date", ex);
        }
    }
}

Related

  1. dateFromString(final String value)
  2. dateFromString(String date)
  3. dateFromString(String date, String pattern)
  4. dateFromString(String dateString)
  5. dateFromString(String dateString)
  6. dateFromString(String value)
  7. DateFromStringFormat(final String date, final String format)
  8. dateFromW3CDTF(String date)
  9. dateParse(String date)