Java String to Date toDate(Object value, String format)

Here you can find the source of toDate(Object value, String format)

Description

Convert the specified object into a Date.

License

Open Source License

Parameter

Parameter Description
value the value to convert
format the DateFormat pattern to parse String values

Exception

Parameter Description
RuntimeException thrown if the value cannot be converted to a Calendar

Return

the converted value

Declaration

public static Date toDate(Object value, String format) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

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

public class Main {
    /**/*  w w w. ja v a  2s  .c o  m*/
     * Convert the specified object into a Date.
     *
     * @param value
     *            the value to convert
     * @param format
     *            the DateFormat pattern to parse String values
     * @return the converted value
     * @throws RuntimeException
     *             thrown if the value cannot be converted to a Calendar
     */
    public static Date toDate(Object value, String format) {
        if (value == null)
            return null;
        if (value instanceof String) {
            try {
                return new SimpleDateFormat(format).parse((String) value);
            } catch (ParseException e) {
                throw new RuntimeException("The value " + value
                        + "with format " + format
                        + " can't be converted to a Date", e);
            }
        } else if (value instanceof Long) {
            return new Date(((Long) value).longValue());
        } else if (value instanceof Date) {
            return (Date) value;
        } else if (value instanceof Calendar) {
            return ((Calendar) value).getTime();
        }
        throw new RuntimeException("The value " + value
                + " can't be converted to a Date");
    }
}

Related

  1. toDate(final String dateString, final String pattern)
  2. toDate(int date, String timeFormat)
  3. toDate(long value, String format)
  4. toDate(Map filter, String field)
  5. toDate(Object v, String format, Date defaultValue)
  6. toDate(String createdAt)
  7. toDate(String d)
  8. toDate(String date)
  9. toDate(String date)