Java Parse Date parseDate(String token)

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

Description

parse Date

License

Open Source License

Declaration

public static Date parseDate(String token) 

Method Source Code


//package com.java2s;
/*/*from  w  ww. ja  v  a2s. c o m*/
 * Copyright (c) 2004 Stephan D. Cote' - All rights reserved.
 * 
 * This program and the accompanying materials are made available under the 
 * terms of the MIT License which accompanies this distribution, and is 
 * available at http://creativecommons.org/licenses/MIT/
 *
 * Contributors:
 *   Stephan D. Cote 
 *      - Initial API and implementation
 */

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

import java.util.Date;

import java.util.List;

public class Main {
    private static final DateFormat _DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
    private static final List<String> formatStrings = Arrays.asList("yyyy-MM-dd'T'HH:mm:ss.SSSX",
            "yyyy-MM-dd'T'HH:mm:ss.SSS", "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd HH:mm:ss.SSSX",
            "yyyy-MM-dd HH:mm:ss.SSS", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd", "MM-dd-yyyy HH:mm:ss.SSSX",
            "MM-dd-yyyy HH:mm:ss.SSS", "MM-dd-yyyy HH:mm:ss", "MM/dd/yyyy HH:mm:ss", "EEE MMM dd HH:mm:ss zzz yyyy",
            "HH:mm:ss.SSSX", "HH:mm:ss.SSS", "HH:mm:ss", "HH:mm", "M/y", "M-y", "M/d/y", "M-d-y", "y/M/d", "y-M-d");

    public static Date parseDate(String token) {
        Date retval = null;
        try {
            retval = _DATE_FORMAT.parse(token);
        } catch (final Exception e) {
            retval = null;
        }
        return retval;
    }

    /**
     * This method tries several different formats to parsing a date.
     * 
     * <p>This method is useful if the actual format of the date is not known.
     * 
     * @param text the date time string to parse
     * 
     * @return the Date reference if parsing was successful or null if the text 
     *         could not be parsed into a date.
     */
    public static Date parse(String text) {
        for (String formatString : formatStrings) {
            try {
                return new SimpleDateFormat(formatString).parse(text);
            } catch (ParseException e) {
            }
        }
        return null;
    }
}

Related

  1. parseDate(String text)
  2. parseDate(String text, String[] datePattern, int index)
  3. parseDate(String time)
  4. parseDate(String time)
  5. parseDate(String timeString)
  6. parseDate(String value)
  7. parseDate(String value)
  8. parseDate(String value)
  9. parseDate(String value)