Java SQL Date From getDateTime(Object value)

Here you can find the source of getDateTime(Object value)

Description

Convert an Object to a DateTime, without an Exception

License

Open Source License

Declaration

public static java.util.Date getDateTime(Object value) 

Method Source Code

//package com.java2s;

import java.text.*;

public class Main {
    public static DateFormat OUT_DATE_FORMAT = new SimpleDateFormat(
            "dd/MM/yyyy");
    public static DateFormat OUT_TIME_FORMAT = new SimpleDateFormat(
            "H:mm:ss");
    public static DateFormat OUT_DATETIME_FORMAT = new SimpleDateFormat(
            "d/M/yyyy H:mm:ss");
    public static DateFormat OUT_TIMESTAMP_FORMAT = new SimpleDateFormat(
            "d/M/yy H:mm:ss.SSS");
    public static DateFormat IN_DATETIME_FORMAT = new SimpleDateFormat(
            "d/M/yy H:mm:ss");

    /**//from  w w  w. j a  v  a2 s .c  o m
     * Convert an Object to a DateTime, without an Exception
     */
    public static java.util.Date getDateTime(Object value) {
        try {
            return toDateTime(value);
        } catch (ParseException pe) {
            pe.printStackTrace();
            return null;
        }
    }

    /**
     * Convert an Object to a DateTime.
     */
    public static java.util.Date toDateTime(Object value)
            throws ParseException {
        if (value == null) {
            return null;
        }
        if (value instanceof java.util.Date) {
            return (java.util.Date) value;
        }
        if (value instanceof String) {
            if ("".equals((String) value)) {
                return null;
            }
            return IN_DATETIME_FORMAT.parse((String) value);
        }

        return IN_DATETIME_FORMAT.parse(value.toString());
    }

    /**
     * Convert an Object to a String using Dates
     */
    public static String toString(Object date) {
        if (date == null) {
            return null;
        }

        if (java.sql.Timestamp.class.isAssignableFrom(date.getClass())) {
            return OUT_TIMESTAMP_FORMAT.format(date);
        }
        if (java.sql.Time.class.isAssignableFrom(date.getClass())) {
            return OUT_TIME_FORMAT.format(date);
        }
        if (java.sql.Date.class.isAssignableFrom(date.getClass())) {
            return OUT_DATE_FORMAT.format(date);
        }
        if (java.util.Date.class.isAssignableFrom(date.getClass())) {
            return OUT_DATETIME_FORMAT.format(date);
        }

        throw new IllegalArgumentException("Unsupported type "
                + date.getClass());
    }
}

Related

  1. getDatabaseLocalTime(Time databaseDate)
  2. getDateTime()
  3. getDateTime()
  4. getDateTime()
  5. getDateTime(final int year, final int month, final int day, final int hour, final int minute, final int second)
  6. toDate(Calendar cal)
  7. toDate(int value)
  8. toDate(java.sql.Date sqlDate)
  9. toDate(java.util.Date date)