Java Time Format stringDateTimeFormat(String dt2Format)

Here you can find the source of stringDateTimeFormat(String dt2Format)

Description

string Date Time Format

License

Apache License

Declaration

public static String stringDateTimeFormat(String dt2Format) 

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";
    private final static String DATETIME_WITHOUT_SS_FORMAT = "yyyy-MM-dd HH:mm";

    public static String stringDateTimeFormat(String dt2Format) {
        return new SimpleDateFormat(DATETIME_WITHOUT_SS_FORMAT).format(parseDateTime(dt2Format));
    }/*from  ww  w  .jav  a2  s  .c om*/

    public static Date parseDateTime(String dateTimeStr) {
        if (dateTimeStr.contains("00:00T")) {
            dateTimeStr = dateTimeStr.replaceFirst("00:00T", "");
        }
        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. printFormatDate(long dateTime)
  2. setDateTimeFormat(String format)
  3. stdTimeFormat(Date date)
  4. string2Long(String sourceTime, String dataFormat)
  5. string2long(String sourceTime, String dataFormat)
  6. stringTimeToLongTime(String time, String format)
  7. stringToTime(String format, String sDate)
  8. time2Date(Integer time, String format)
  9. time2String(Date time, DateFormat dateFormat)