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:
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);
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.