0

Here is my code in Java 1.6 (question was marked duplicate but suggested solution refers to java 1.8)

public static void main(String[] args){
    try{
        String dateTimeString = "2015-08-10-14.20.40.679279";
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.SSSSSS");
        java.util.Date formattedDate = dateFormat.parse(dateTimeString);
        Timestamp formattedTime = new Timestamp(formattedDate.getTime());
        System.out.println(formattedTime);
    } catch (Throwable t){
        t.printStackTrace();
    }
}

The resulted object is: 2015-08-10 14:31:59.279, so clearly something is wrong while parsing minutes, seconds and millis, I just don't know what exactly.
Thank you!

assylias
  • 321,522
  • 82
  • 660
  • 783
urir
  • 1,960
  • 3
  • 23
  • 40
  • 1
    What is `679279`? millis (doesn't look right)? fraction of seconds (i.e. microseconds, in which case you need to get rid of the last 3 digits because the date API only supports millis)? – assylias Apr 26 '16 at 16:08
  • The bulk of that mentioned Java 8 (java.time) functionality is back-ported to Java 6 & 7 in the [ThreeTen-Backport](http://www.threeten.org/threetenbp/) project. A vast improvement over the troublesome legacy classes you are using here. And the java.time classes use nanosecond resolution (9 decimal places) so it can accommodate your microseconds data (6 decimal places) with no data loss and no hassle. – Basil Bourque Apr 26 '16 at 20:33

2 Answers2

2

There is no something like SSSSSS. Check Simple Date Format manual

mariusz2108
  • 851
  • 2
  • 11
  • 36
1

You have to drop out the last 3 msec:

Date d = ( new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.SSS", Locale.US) ).parse("2015-08-10-14.20.40.679279");
        System.out.println(new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.S").format(d));
        System.out.println(new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.SS").format(d));
        System.out.println(new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.SSS").format(d));

        Date dd = ( new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.SSS", Locale.US) ).parse("2015-08-10-14.20.40.679");
        System.out.println(new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.S").format(dd));
        System.out.println(new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.SS").format(dd));
        System.out.println(new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.SSS").format(dd));

to get the right formatting:

2015-08-10-14.31.59.279
2015-08-10-14.31.59.279
2015-08-10-14.31.59.279
2015-08-10-14.20.40.679
2015-08-10-14.20.40.679
2015-08-10-14.20.40.679

Check it out this playground.

loretoparisi
  • 15,724
  • 11
  • 102
  • 146