Java Parse Date parseDateTime(String dateTimeStr)

Here you can find the source of parseDateTime(String dateTimeStr)

Description

parse Date Time

License

Apache License

Declaration

public static Date parseDateTime(String dateTimeStr) 

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 Pattern DATETIME_PATTERN = Pattern
            .compile("\\d\\d\\d\\d-\\d\\d?-\\d\\d?T\\d\\d?:\\d\\d?:\\d\\d?");
    private final static String DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss";
    private final static String DATETIME_FORMAT_NoT = "yyyy-MM-dd HH:mm:ss";

    public static Date parseDateTime(String dateTimeStr) {
        if (dateTimeStr.contains("00:00T")) {
            dateTimeStr = dateTimeStr.replaceFirst("00:00T", "");
        }/*w  w  w. ja v a 2  s.  c om*/
        try {
            if (isValidDateTimeString(dateTimeStr)) {
                return (new SimpleDateFormat(DATETIME_FORMAT).parse(dateTimeStr));
            } else if (isValidDateString(dateTimeStr)) {
                return (new SimpleDateFormat(DATETIME_FORMAT).parse(dateTimeStr.concat("T00:00:00")));
            } else {
                return (new SimpleDateFormat(DATETIME_FORMAT_NoT).parse(dateTimeStr));
            }

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

    public static boolean isValidDateTimeString(String dateTimeStr) {
        return dateTimeStr == null ? false : DATETIME_PATTERN.matcher(dateTimeStr).matches();
    }

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

Related

  1. parseDateTime(String d, String t)
  2. parseDateTime(String date)
  3. parseDateTime(String date, String format, String locale, String timeZone)
  4. parseDateTime(String date, String time)
  5. parseDateTime(String dateTime)
  6. parseDateTime(String dateTimeString)
  7. parseDateTime(String dateTimeString)
  8. parseDateTime(String dateTimeString, String[] validFormats, String outputFormat)
  9. parseDateTime(String format, String dateStr)