Java Parse Time parseTime(String token)

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

Description

parse Time

License

Open Source License

Declaration

public static Date parseTime(String token) 

Method Source Code


//package com.java2s;
/*/*from www  . j  ava 2  s. c om*/
 * 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 _TIME_FORMAT = new SimpleDateFormat("HH:mm:ss");
    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 parseTime(String token) {
        Date retval = null;
        try {
            retval = _TIME_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. parseTime(String time)
  2. parseTime(String time)
  3. parseTime(String time, String formatStrBefore, String formatStrAfter)
  4. parseTime(String timestring)
  5. parseTime(String timeString, TimeZone timeZone)
  6. parseTimeConfiguration(String time)
  7. parseTimeSpec(String[] spec)
  8. parseTimeStr(String timeStr)
  9. parseTimeString(String time)