Java Date Create castToDate(Object value)

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

Description

cast To Date

License

Apache License

Declaration

public static final Date castToDate(Object value) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

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

public class Main {
    public static final Date castToDate(Object value) {
        if (value == null) {
            return null;
        }/*from w w  w. j a va2  s. c  o m*/

        if (value instanceof Calendar) {
            return ((Calendar) value).getTime();
        }

        if (value instanceof Date) {
            return (Date) value;
        }

        long longValue = -1;

        if (value instanceof Number) {
            longValue = ((Number) value).longValue();
            return new Date(longValue);
        }

        if (value instanceof String) {
            String strVal = (String) value;

            if (strVal.indexOf('-') != -1) {
                String format;
                if (strVal.length() == "yyyy-MM-dd HH:mm:ss".length()) {
                    format = "yyyy-MM-dd HH:mm:ss";
                } else if (strVal.length() == 10) {
                    format = "yyyy-MM-dd";
                } else {
                    format = "yyyy-MM-dd HH:mm:ss.SSS";
                }

                SimpleDateFormat dateFormat = new SimpleDateFormat(format);
                try {
                    return (Date) dateFormat.parse(strVal);
                } catch (ParseException e) {
                    throw new IllegalArgumentException("can not cast to Date, value : " + strVal);
                }
            }

            if (strVal.length() == 0) {
                return null;
            }

            longValue = Long.parseLong(strVal);
        }

        if (longValue < 0) {
            throw new IllegalArgumentException("can not cast to Date, value : " + value);
        }

        return new Date(longValue);
    }
}

Related

  1. buildDate(String dateAsString)
  2. buildDateFormat(final String pattern)
  3. buildDatetime(Date datePart, Date hourMinutePart)
  4. buildDateTime(String curDate, String curTime, String meridiem)
  5. buildDateTimeUTC(Calendar cal)
  6. create(int year, int month, int date, TimeZone timeZone)
  7. createDate(final Date date)
  8. createDate(final Date date)
  9. createDate(final int aYear, final int aMonth, final int aDate, final int aHour, final int aMinute, final int aSecond)