Search code examples
javatimestampparseexception

Convert String to Timestamp Java


So I am having this issue that I can't wrap my head around. I've read similar questions posed but very case I've found there is an issue with the format, and my format is correct.

Basically I am trying to convert a String into a Timestamp, and I get the unparseable date error.

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Hello {

public static Timestamp convertStringToTimestamp(String str_date) {
    try {

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS");
        Date date = formatter.parse(str_date);
        java.sql.Timestamp timeStampDate = new Timestamp(date.getTime());
        return timeStampDate;

    } catch (ParseException e) {
        System.out.println("Exception :" + e);
        return null;
    }
}

public static void main(String[] args) {
    Timestamp ts = convertStringToTimestamp("2015-06-09 11:51:12,708");
    Timestamp ts2 = convertStringToTimestamp("2015-04-17 11:29:49.564");
    System.out.println(ts +" | "+ts2);


}

}

Output:

Exception :java.text.ParseException: Unparseable date: "2015-06-09 11:51:12,708"
Exception :java.text.ParseException: Unparseable date: "2015-04-17 11:29:49.564"
null | null

Any ideas?


Solution

  • **Update**
    import java.sql.Timestamp;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    
    public class SomeClass {
    
        public static void main(String[] args) {
    
    
             System.out.println(convertStringToTimestamp("2015-06-09 11:51:12,708"));
             //be consistent here with , and .
             System.out.println(convertStringToTimestamp("2015-04-17 11:29:49.564"));
             System.out.println();
    
    
        }
    
        private static Timestamp  convertStringToTimestamp(String something) {
    
    
    SimpleDateFormat dateFormat = null;
            if(something.contains(".")) {
                dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
            } 
            if(something.contains(",")) {
                dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss,SSS");
            }
            Timestamp timestamp = null;
                Date parsedDate;
                try {
                    parsedDate = dateFormat.parse(something);
                     timestamp = new java.sql.Timestamp(parsedDate.getTime());
    
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
    
                return timestamp;
        }
    
    
    
    }