Java String to Date stringToDate(String source, String format)

Here you can find the source of stringToDate(String source, String format)

Description

string To Date

License

Open Source License

Declaration

public static Date stringToDate(String source, String format) 

Method Source Code


//package com.java2s;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
    public static final String DATE_PATTERN_SS = "yyyyMMddHHmmssSS";
    private static final String INIT_DATE_TIME = "1900-01-01 00:00:00";

    public static Date stringToDate(String source, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);

        try {/*from w  w  w  . ja  v a2  s .  co  m*/
            if (format.equals(YYYY_MM_DD_HH_MM_SS) || format.equals(DATE_PATTERN_SS)) {
                if (source.length() < INIT_DATE_TIME.length()) {
                    source += INIT_DATE_TIME.substring(source.length() + 1);
                }
            }
            return sdf.parse(source);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Date stringToDate(Date date, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        try {
            return sdf.parse(dateToString(new Date(), format));
        } catch (Exception e) {
            return null;
        }
    }

    public static Date parse(String str) {
        SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
        try {
            if (str.length() < INIT_DATE_TIME.length()) {
                str += INIT_DATE_TIME.substring(str.length() + 1);
            }
            return sdf.parse(str);
        } catch (ParseException e) {
            return null;
        }
    }

    public static String dateToString(Date date, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        try {
            return sdf.format(date);
        } catch (Exception e) {
            return null;
        }
    }

    public static String format(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
        return sdf.format(date);
    }

    public static String format(Date date, String pattern) {
        return date == null ? " " : new SimpleDateFormat(pattern).format(date);
    }

    public static String format() {
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_PATTERN_SS);
        return sdf.format(new Date());
    }
}

Related

  1. StringToDate(String s)
  2. stringToDate(String s, DateFormat formatter)
  3. stringToDate(String s, String format)
  4. stringToDate(String sDate)
  5. stringToDate(String source)
  6. StringToDate(String str)
  7. stringToDate(String str)
  8. stringToDate(String str, String format)
  9. StringToDate(String str, String format)