I have a problem where SimpleDateFormat and Date and Timestamp are giving a time that is off by a few minutes (approximately 34 minutes for one string and approximately 1:27 for an other string). I have been able to find several posts on SimpleDateFormat etc. giving incorrect times but the ones I have found all relate to yyyy v. YYYYY, or timezone, or Sql timestamps, or other issues that cause the date to be off by relatively round numbers. For example:
Java SimpleDateFormat: an hour wrong
SimpleDateFormat returns wrong date value during parse
Java SimpleDateFormat returning wrong value in Date object
SimpleDateFormat parse returns wrong value
JDBC ResultSet getDate losing precision
SimpleDateFormat producing wrong date time when parsing "YYYY-MM-dd HH:mm"
Why does the code below give the output shown and how can I get the string representing the time to parse correctly?
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimeExample {
public static void main(String[] args) throws Exception {
toTimeStamp("2016-01-06 10:03:55.2000000");
toTimeStamp("2016-01-06 09:48:05.5230000");
}
public static void toTimeStamp(String str) throws Exception {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd' 'HH:mm:ss.SSSSSSS");
Date date = format.parse(str);
Timestamp ts = new Timestamp(date.getTime());
System.out.println("----------------------------");
System.out.println(str);
System.out.println(ts);
}
}
Output:
----------------------------
2016-01-06 10:03:55.2000000
2016-01-06 10:37:15.0
----------------------------
2016-01-06 09:48:05.5230000
2016-01-06 11:15:15.0