Java - Write code to convert String To TimeStamp

Requirements

Write code to convert String To TimeStamp

Demo

//package com.book2s;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;

public class Main {
    public static void main(String[] argv) {
        String sMt = "12:12:12";
        System.out.println(convertStringToTimeStamp(sMt));
    }//www. jav  a 2  s  . com

    public static Timestamp convertStringToTimeStamp(String sMt) {
        Timestamp result = null;
        try {
            java.util.Date utilDate = null;
            if (sMt != null && sMt.length() > 0) {
                int length = sMt.length();

                if (length > 17) {
                    utilDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                            .parse(sMt);
                } else if (length > 13) {
                    utilDate = new SimpleDateFormat("yyyy-MM-dd HH:mm")
                            .parse(sMt);
                } else if (length >= 10) {
                    utilDate = new SimpleDateFormat("yyyy-MM-dd")
                            .parse(sMt);
                } else if (length >= 8) {
                    utilDate = new SimpleDateFormat("HH:mm:ss").parse(sMt);
                } else if (length == 7) {
                    utilDate = new SimpleDateFormat("yyyy-MM").parse(sMt);
                } else if (length == 5) {
                    utilDate = new SimpleDateFormat("HH:mm").parse(sMt);
                }

                result = new Timestamp(utilDate.getTime());

            }
        } catch (Exception e) {
        }

        return result;
    }
}

Related Exercise