0

I know that there many subject of how to convert from String to Date, I'm using 'SimpleDateFormat' and i have a string that contains (Year, Month, Day , Hour, Minute, second, Milliseconds) but when I'm using the 'SimpleDateFormat' the Milliseconds is not set here the code and the output:

import java.text.SimpleDateFormat;
import java.util.Date;

String strDate = "2020-08-27T10:06:07.413";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
Date dateFormatter = formatter.parse(strDate);

System.out.println(dateFormatter);

Output:

Thu Aug 27 10:06:07 WAT 2020

I want the result in type Date

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
Mohamed Drira
  • 52
  • 1
  • 7
  • 6
    Use `java.time` and stop using `java.util.Date` as well as `java.text.SimpleDateFormat`... Is your system time zone West Africa Time? – deHaar Aug 28 '20 at 09:33
  • I want Date as type of result, I've edited the question (adding the imports), I don't know how to use java.time in this type of example – Mohamed Drira Aug 28 '20 at 09:39
  • 1
    How do you output the `Date`? Can you show us that line of code? – deHaar Aug 28 '20 at 09:42
  • I using Sout(), , I've edited the question (adding the sout) – Mohamed Drira Aug 28 '20 at 09:44
  • To see the millis in output you need to print the parsed date using format, not just `System.out.println(dateFormatter);` Default format in `Date.toString` is not set up to display millis. And yes, `Date`/`Calendar`/`SimpleDateFormatter` are outdated for a long time and their use is severely discouraged. Please use Java 8 Date-Time API defined in `java.time` package. – Nowhere Man Aug 28 '20 at 09:46
  • Related and probably helpful: (1) [Insert & fetch java.time.LocalDate objects to/from an SQL database such as H2](https://stackoverflow.com/questions/43039614/insert-fetch-java-time-localdate-objects-to-from-an-sql-database-such-as-h2) (2) [Getting the date from a ResultSet for use with java.time classes](https://stackoverflow.com/questions/29773390/getting-the-date-from-a-resultset-for-use-with-java-time-classes). – Ole V.V. Aug 30 '20 at 18:37

3 Answers3

3

The Date class stores the time as milliseconds, and if you look into your date object you will see that it actually has a time of 1598515567413 milliseconds.

You are fooled by the System.out.println() which uses Date's toString() method. This method is using the "EEE MMM dd HH:mm:ss zzz yyyy" format to display the date and simply omits all milliseconds.

If you use your formatter, which has milliseconds in its format string, you will see that the milliseconds are correct:

System.out.println(formatter.format(dateFormatter));

outputs 2020-08-27T10:06:07.413

schrom
  • 1,372
  • 1
  • 22
  • 36
2

You can use:

String strDate = "2020-08-27T10:06:07.413"

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
DateTime datetimeDF = formatter.parseDateTime(strDate);
String text = formatter.print(datetimeDF);

System.out.println(text);

Or you can use java.time:

String strDate = "2020-08-27T10:06:07.413"
LocalDateTime ldate = LocalDateTime.parse(datetime, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS"));

and use the object ldate as you want.

yaylitzis
  • 5,354
  • 17
  • 62
  • 107
2

Update (based on OP's comment):

You have mentioned: Thanks that was realy heplful I've allready tried the java.util but i could not set the date in the database using LocalDateTime that's why I'm using Date

You've to use PreparedStatement#setObject to set LocalDate into the database table e.g.

LocalDate localDate = LocalDate.now();
PreparedStatement st = conn.prepareStatement("INSERT INTO mytable (columnfoo) VALUES (?)");
st.setObject(1, localDate);
st.executeUpdate(); 
st.close();

Original answer:

Given below is the toString implementation of java.util.Date:

public String toString() {
    // "EEE MMM dd HH:mm:ss zzz yyyy";
    BaseCalendar.Date date = normalize();
    StringBuilder sb = new StringBuilder(28);
    int index = date.getDayOfWeek();
    if (index == BaseCalendar.SUNDAY) {
        index = 8;
    }
    convertToAbbr(sb, wtb[index]).append(' ');                        // EEE
    convertToAbbr(sb, wtb[date.getMonth() - 1 + 2 + 7]).append(' ');  // MMM
    CalendarUtils.sprintf0d(sb, date.getDayOfMonth(), 2).append(' '); // dd

    CalendarUtils.sprintf0d(sb, date.getHours(), 2).append(':');   // HH
    CalendarUtils.sprintf0d(sb, date.getMinutes(), 2).append(':'); // mm
    CalendarUtils.sprintf0d(sb, date.getSeconds(), 2).append(' '); // ss
    TimeZone zi = date.getZone();
    if (zi != null) {
        sb.append(zi.getDisplayName(date.isDaylightTime(), TimeZone.SHORT, Locale.US)); // zzz
    } else {
        sb.append("GMT");
    }
    sb.append(' ').append(date.getYear());  // yyyy
    return sb.toString();
}

As you can see in this implementation, it doesn't include milliseconds and therefore if you print date as in the following code, you will get what the Date#toString returns and thus, you won't see milliseconds in the output.

String strDate = "2020-08-27T10:06:07.413";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
Date date= formatter.parse(strDate);
System.out.println(date);

I assume that you already know that System.out.println(obj) prints the string returned by obj.toString().

How can you get output in a custom format?

You have two options:

  1. Recommended option: Use a date-time formatter e.g. SimpleDateFormat as shown below:

    String strDate = "2020-08-27T10:06:07.413";
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
    Date date = formatter.parse(strDate);
    System.out.println(date);
    
    String dateStr = formatter.format(date);
    System.out.println(dateStr);
    
  2. Override toString implementation of Date by creating a custom class by extending java.util.Date. Although it's an option, I never recommend this to do.

Finally, a piece of advice:

Stop using the outdated and error-prone java.util date-time API and SimpleDateFormat. Switch to the modern java.time date-time API and the corresponding formatting API (java.time.format). Learn more about the modern date-time API from Trail: Date Time.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110