Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse time with microseconds in Java

Tags:

java

I am having problems parsing time strings in Java that are in the format of 2013-01-09 09:15:03.000000. In my data, the last three digits are always 0 (meaning the input strings have only millisecond precision), so I passed this format to SimpleDateFormat:

formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS'000'");

but formatter.parse("2013-01-09 09:15:02.500000"); throws an exception:

Unparseable date: "2013-01-09 09:15:02.500000"
    at java.text.DateFormat.parse(DateFormat.java:357)

Anyone knows how to do it correctly? I can work around by using format yyyy-MM-dd HH:mm:ss.SSS and using substring to get rid of last three digits but that's really hacky.

EDIT: can anyone explain why the format string yyyy-MM-dd HH:mm:ss.SSS'000' can't be used to parse time "2013-01-09 09:15:02.500000"

like image 453
Kan Li Avatar asked Apr 09 '14 04:04

Kan Li


1 Answers

try java.sql.Timestamp

     Timestamp ts = Timestamp.valueOf("2013-01-09 09:15:03.500000"); 
     Date date = new Date(ts.getTime())

it's also thread-safe and fast as opposed to SimpleDateFormat

like image 125
Evgeniy Dorofeev Avatar answered Oct 26 '22 19:10

Evgeniy Dorofeev