Java Timestamp Create toTimestamp(String dt)

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

Description

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

License

Open Source License

Parameter

Parameter Description
dt String (yyyyMMdd or yyyyMMddHHmmss)

Return

java.sql.Timestamp

Declaration

public static java.sql.Timestamp toTimestamp(String dt) 

Method Source Code

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

import java.util.Calendar;

public class Main {
    /**// w  ww .  j  av a 2s.c o m
    * convert date String (yyyyMMdd or yyyyMMddHHmmss) to java.sql.Timestamp
    * @param dt String (yyyyMMdd or yyyyMMddHHmmss)
    * @return java.sql.Timestamp
    */
    public static java.sql.Timestamp toTimestamp(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 new java.sql.Timestamp(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. toTimestamp(Object dateobj)
  2. toTimestamp(Object objInParam)
  3. toTimestamp(String _sDate)
  4. toTimestamp(String dateTime)
  5. toTimestamp(String dateTime)
  6. toTimestamp(String s)
  7. toTimeStamp(String sDate, String format)
  8. toTimestamp(String str, String format)
  9. toTimestamp(String value)