Android Timestamp String to Timestamp Convert str2Timestamp(String str)

Here you can find the source of str2Timestamp(String str)

Description

str Timestamp

Declaration

public static Timestamp str2Timestamp(String str) 

Method Source Code

//package com.java2s;
import java.sql.Timestamp;
import java.util.Calendar;

import java.util.GregorianCalendar;

public class Main {
    public static Timestamp str2Timestamp(String str) {
        if (str == null)
            return null;
        str = str.trim();//  ww w  .j  a v a  2 s.  co m
        if (!str.matches("^\\d\\d\\d\\d-\\d\\d-\\d\\d$")
                && !str.matches("^\\d\\d\\d\\d-\\d\\d-\\d\\d \\d\\d:\\d\\d:\\d\\d$"))
            return null;

        String[] ss = str.split("-| |:");
        GregorianCalendar gc = new GregorianCalendar();
        gc.set(Calendar.YEAR, Integer.parseInt(ss[0]));
        gc.set(Calendar.MONTH, Integer.parseInt(ss[1]) - 1);
        gc.set(Calendar.DAY_OF_MONTH, Integer.parseInt(ss[2]));
        if (ss.length == 6) {
            gc.set(Calendar.HOUR_OF_DAY, Integer.parseInt(ss[3]));
            gc.set(Calendar.MINUTE, Integer.parseInt(ss[4]));
            gc.set(Calendar.SECOND, Integer.parseInt(ss[5]));
        }
        return new Timestamp(gc.getTimeInMillis());
    }
}

Related

  1. stringConvertTimestamp(String time)
  2. serverTimestampToDate(String timestamp)