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.
SimpleDateF
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());
All you need to do is change the string within the java.text.SimpleDateFormat constructor to: "MM-dd-yyyy HH:mm:ss".
Just use the appropriate letters to build the above string to match your input date.
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 formatIf 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 ) ;
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 capital HH
to get hour of day format, instead of am/pm hours
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 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.
}