0

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
Community
  • 1
  • 1
John
  • 3,458
  • 4
  • 33
  • 54
  • 1
    Also [SimpleDateFormat showing minutes, seconds and milliseconds wrong](http://stackoverflow.com/questions/29828447/simpledateformat-showing-minutes-seconds-and-milliseconds-wrong). – rgettman Jan 06 '16 at 18:28
  • Yes, an exact duplicate of what @rgettman linked: using only `SSS` and the corresponding correct amount of 0s yields the correct result. – luk2302 Jan 06 '16 at 18:33
  • Yup, the other post definitely asks and answers my question. What is the appropriate etiquette here? Do I delete this question or just let it stand? – John Jan 06 '16 at 18:34
  • Go ahead and delete it. It's of no help to anyone else searching for similar issue, as they should find the linked question instead, unless you think you're using keywords in your question that provide a better search result. – Andreas Jan 06 '16 at 18:37

0 Answers0