Java Date Parse getDateFromStr(DateFormat format, String s)

Here you can find the source of getDateFromStr(DateFormat format, String s)

Description

get Date From Str

License

Open Source License

Declaration

public static Date getDateFromStr(DateFormat format, String s) 

Method Source Code

//package com.java2s;

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

import java.util.Date;

import java.util.TimeZone;

public class Main {
    public final static DateFormat format_yyyyMMdd_HHmmss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public final static DateFormat format_yyyyMMdd = new SimpleDateFormat("yyyy-MM-dd");
    public final static DateFormat format13 = new SimpleDateFormat("yyyy-MM-dd HH:mm");

    public static Date getDateFromStr(DateFormat format, String s) {
        if (s == null || s.trim().equals("")) {
            return null;
        }/*from  w w  w  . java  2s.c o  m*/
        if (format == null) {
            if (s.length() == 10) {
                format = format_yyyyMMdd;
            } else if (s.length() == 16) {
                format = format13;
            } else {
                format = format_yyyyMMdd_HHmmss;
            }
        }
        return parseDateStringToDate(format, s);
    }

    public static Date parseDateStringToDate(DateFormat format, String dateString) {
        if (format != null) {
            synchronized (format) {
                try {
                    return format.parse(dateString);
                } catch (ParseException e) {
                    return null;
                }
            }
        } else {
            // String message = "format is null,the dataString is " +
            // dateString;
            return null;
        }

    }

    public static Date parseDateStringToDate(DateFormat format, String time, TimeZone timeZone) {
        synchronized (format) {
            try {
                format.setTimeZone(timeZone);
                return format.parse(time);
            } catch (ParseException e) {
                return null;
            }
        }
    }
}

Related

  1. getDateFromOffset(Date prevDate, int offset)
  2. getDateFromOriDateStr(String strDate)
  3. getDateFromRange(String date)
  4. getDateFromRequestStringDate(String dateString)
  5. getDateFromRFC822String(Object rfc822)
  6. getDateFromStr(String date)
  7. getDateFromStr(String inputDate, String inputFormatStr)
  8. getDateFromString(final String dateStr, final String pattern)
  9. getDateFromString(final String dateString, final String dateFormatString)