Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String to Date, DateFormat not working

I'm having a little difficulty converting a string of the below format into a date. Keeps throwing a ParseException.

String: 2015-11-14 17:29:16.543934

I've looked around here already, notably this link: Java string to date conversion, but not having any luck.

Here's what my method currently looks like:

private Date parseTime(String input) {
    // input format: 2015-11-14 17:29:16.543934
    try {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssSSSSSS");
        Date date = format.parse(input);
        return date;
    } catch (ParseException e) {
        System.out.println("Could not parse time. ID: " + this.id);
    }
    return null;
}

EDIT:

On the answer I gave below (stating I missed a "." between the seconds and millis) Jon Skeet had a very good point: "That still won't work as you expect it to. It will treat your input as having 543934 milliseconds... so it will parse as being 17:38:19."

I actually don't need this level of precision so I'm just going to cut off the milliseconds, but if anyone knows how to keep the precision of 6 decimal points I would be interested to know how.

like image 360
JChristen Avatar asked Jun 23 '26 10:06

JChristen


1 Answers

You are missing the dot at the string format:

ss.SSSSSS

it must be:

DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
like image 157
ΦXocę 웃 Пepeúpa ツ Avatar answered Jun 26 '26 00:06

ΦXocę 웃 Пepeúpa ツ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!