Java Timestamp from convertString2Timestamp(String value)

Here you can find the source of convertString2Timestamp(String value)

Description

convert String Timestamp

License

Open Source License

Declaration

public static java.sql.Timestamp convertString2Timestamp(String value) 

Method Source Code


//package com.java2s;

import java.sql.Timestamp;

import java.util.Calendar;
import java.util.GregorianCalendar;

public class Main {

    public static java.sql.Timestamp convertString2Timestamp(String value) {
        java.sql.Timestamp out = null;
        if (value == null) {
            out = new java.sql.Timestamp(0);
        } else {/*from   w  ww.  j  av a  2  s . co m*/
            try {
                String v = value.toString().trim();
                if (v.length() == 8) { // yyyyMMdd
                    String yearString = v.substring(0, 4);
                    String monthString = v.substring(4, 6);
                    String dayString = v.substring(6, 8);
                    int year = Integer.parseInt(yearString);
                    int month = Integer.parseInt(monthString) - 1;
                    int day = Integer.parseInt(dayString);
                    Calendar cal = new GregorianCalendar();
                    cal.set(year, month, day);
                    out = new Timestamp(cal.getTime().getTime());

                } else if (v.length() == 14 || v.length() == 17) { // yyyyMMddHHmmss
                    String yearString = v.substring(0, 4);
                    String monthString = v.substring(4, 6);
                    String dayString = v.substring(6, 8);
                    String hourString = v.substring(8, 10);
                    String minString = v.substring(10, 12);
                    String secString = v.substring(12, 14);
                    int year = Integer.parseInt(yearString);
                    int month = Integer.parseInt(monthString) - 1;
                    int day = Integer.parseInt(dayString);
                    int hour = Integer.parseInt(hourString);
                    int min = Integer.parseInt(minString);
                    int sec = Integer.parseInt(secString);
                    Calendar cal = new GregorianCalendar();
                    cal.set(year, month, day, hour, min, sec);
                    out = new Timestamp(cal.getTime().getTime());

                }
            } catch (Exception e) {
                out = new java.sql.Timestamp(0);
            }
        }
        return out;
    }
}

Related

  1. convertDateToTimestamp(Date date)
  2. convertDateToTimestamp(java.util.Date date)
  3. convertLongToTimestamp(Long millSec)
  4. convertSQLTimestamp(String s, String formatIn, String formatOut)
  5. convertString2TimeStamp(String dateString)
  6. convertStringDateToTimestamp(String sDate, String dateformat)
  7. convertStringToTimeStamp(String date)
  8. convertStringToTimestamp(String str)
  9. convertToTimestamp(Date aJavaDate)