Java SQL Date From toSQLDate(String dt)

Here you can find the source of toSQLDate(String dt)

Description

convert date String (yyyyMMdd or yyyyMMddHHmmss) to java.sql.Date

License

Open Source License

Parameter

Parameter Description
dt String (yyyyMMdd or yyyyMMddHHmmss)

Return

java.sql.Date

Declaration

public static java.sql.Date toSQLDate(String dt) 

Method Source Code

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

import java.util.Calendar;

public class Main {
    /**/* w  w  w.  j  a  v a 2  s .  c om*/
    * convert date String (yyyyMMdd or yyyyMMddHHmmss) to java.sql.Date
    * @param dt String (yyyyMMdd or yyyyMMddHHmmss)
    * @return java.sql.Date
    */
    public static java.sql.Date toSQLDate(String dt) {
        return new java.sql.Date(toUtilDate(dt).getTime());
    }

    public static java.util.Date toUtilDate(long dt) {
        return new java.util.Date(dt);
    }

    /**
    * convert date String (yyyyMMdd or yyyyMMddHHmmss) to java.util.Date
    * @param dt String (yyyyMMdd or yyyyMMddHHmmss)
    * @return java.util.Date
    */
    public static java.util.Date toUtilDate(String dt) {
        if (dt == null) {
            throw new IllegalArgumentException("dt can not be null");
        }

        int len = dt.length();
        if (!(len == 8 || len == 14)) {
            throw new IllegalArgumentException("dt length must be 8 or 14 (yyyyMMdd or yyyyMMddHHmmss)");
        }

        if (dt.length() == 8) {
            dt += "000000";
        }

        return getDate(dt);
    }

    /**
    * yyyyMMddHHmmss --> java.util.Date
    * @param String dt
    * @return java.util.Date
    */
    private static java.util.Date getDate(String dt) {
        Calendar cal = Calendar.getInstance();
        cal.set(Integer.valueOf(dt.substring(0, 4)).intValue(), Integer.valueOf(dt.substring(4, 6)).intValue() - 1,
                Integer.valueOf(dt.substring(6, 8)).intValue(), Integer.valueOf(dt.substring(8, 10)).intValue(),
                Integer.valueOf(dt.substring(10, 12)).intValue(), Integer.valueOf(dt.substring(12, 14)).intValue());

        return cal.getTime();
    }
}

Related

  1. toSQLDate(java.util.Date date)
  2. toSQLDate(Object object, Object oDefault)
  3. toSqlDate(String date)
  4. toSqlDate(String date)
  5. toSqlDate(String dateStr, String format)
  6. toSQLDate(String sDate, String format)
  7. toSqlDateFromStrDate(String p_strDate)
  8. toSqlDateJdbcEscape(final String str)
  9. toSqlDateString(java.sql.Date d, String pattern)