[java] How to convert string date to Timestamp in java?

I want to convert string Date into Timestamp in java. The following coding i have written.I have declare the date for date1 is: 7-11-11 12:13:14.

SimpleDateFormat datetimeFormatter1 = new SimpleDateFormat(
                "yyyy-MM-dd hh:mm:ss");
Date lFromDate1 = datetimeFormatter1.parse(date1);
System.out.println("gpsdate :" + lFromDate1);
Timestamp fromTS1 = new Timestamp(lFromDate1.getTime());

I want to convert 7-11-11 12:13:14 this string date into timestamp. Now i got the output is 0007-11-11 00:13:14.000000 +05:30:00 but i want ( 7-11-11 12:13:14) this format Timestamp date. Can anyone please help me. Thank you.

This question is related to java

The answer is


Use capital HH to get hour of day format, instead of am/pm hours


tl;dr

java.sql.Timestamp                  
.valueOf(                           // Class-method parses SQL-style formatted date-time strings.
    "2007-11-11 12:13:14"
)                                   // Returns a `Timestamp` object.
.toInstant()                        // Converts from terrible legacy classes to modern *java.time* class.

java.sql.Timestamp.valueOf parses SQL format

If you can use the full four digits for the year, your input string of 2007-11-11 12:13:14 would be in standard SQL format assuming this value is meant to be in UTC time zone.

The java.sql.Timestamp class has a valueOf method to directly parse such strings.

String input = "2007-11-11 12:13:14" ;
java.sql.Timestamp ts = java.sql.Timestamp.valueOf( input ) ;

java.time

In Java 8 and later, the java.time framework makes it easier to verify the results. The j.s.Timestamp class has a nasty habit of implicitly applying your JVM’s current default timestamp when generating a string representation via its toString method. In contrast, the java.time classes by default use the standard ISO 8601 formats.

System.out.println( "Output: " + ts.toInstant().toString() );

Use below code to convert String Date to Epoc Timestamp. Note : - Your input Date format should match with SimpleDateFormat.

String inputDateInString= "8/15/2017 12:00:00 AM";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyy hh:mm:ss");

Date parsedDate = dateFormat.parse("inputDateInString");

Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());

System.out.println("Timestamp "+ timestamp.getTime());

You can convert String to Timestamp:

String inDate = "01-01-1990"
DateFormat df = new SimpleDateFormat("MM-dd-yyyy");
Timestamp ts = new Timestamp(((java.util.Date)df.parse(inDate)).getTime());

You can even try this.

   String date="09/08/1980";    // take a string  date
    Timestamp ts=null;  //declare timestamp
    Date d=new Date(date); // Intialize date with the string date
    if(d!=null){  // simple null check
        ts=new java.sql.Timestamp(d.getTime()); // convert gettime from date and assign it to your timestamp.
    }