Convert SQL date to Java.util.date - java

My requirement is to return the dueDate field as a date to the calling service.
The back end code returns the date in mm/dd/yy. When I map those fields to the Java code, my object contains the date field of type java.sql.Date.
The field that is defined in the object is (note it's the pseudo):
import java.sql.Date;
private Date dueDate;
/**
* #return the dueDate
*/
public Date getDueDate() {
return dueDate;
}
/**
* #param DueDate the DueDate to set
*/
public void setDueDate(Date dueDate) {
this.dueDate = dueDate;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("DueDetails [dueAmount=").append(dueAmount).append(", dueDate=").append(dueDate)
.append("]");
return builder.toString();
}
When I print the object, the Date field comes in this form:
dueDate=Thu Oct 25 20:00:00 EDT 2018
dueDate=Thu Aug 02 20:00:00 EDT 2018
When I query from backend, it shows me the proper format (mm/dd/yy), which I should return to the calling service.

check this
//converting java.util.Date to java.sql.Date in Java
java.sql.Date sqlDate = new java.sql.Date(now.getTime());
System.out.println("Converted value of java.sql.Date : " + sqlDate);
//converting java.sql.Date to java.util.Date back
java.util.Date utilDate = new java.util.Date(sqlDate.getTime());
System.out.println("Converted value of java.util.Date : " + utilDate);
from this link: http://www.java67.com/2012/12/how-to-convert-sql-date-to-util-date.html
Then you can use SimpleDateFormat to format the date as you like:
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String strdate = simpleDateFormat.format(myJavaDate);
System.out.println(strdate);

java.util.Date vs java.sql.Date
Your output looks to be coming from a java.util.Date rather than a java.sql.Date.
It is unfortunately easy to mixup the two. Besides the Date name, the sql one technically is a subclass of the other util one. Beware: This is a hack, and a bad hack at that. The documentation warns us to pretend the two are not in an inheritance relationship. But the compiler does not know that.
Here is some example code showing these two classes and the different behavior of their respective toString method.
// Legacy classes
System.out.println( "java.sql.Date: " + new java.sql.Date( Instant.now().toEpochMilli() ) ) ;
System.out.println( "java.util.Date: " + new java.util.Date() ) ;
See this code run live at IdeOne.com.
java.sql.Date: 2018-07-31
java.util.Date: Tue Jul 31 22:44:14 GMT 2018
You can see the java.sql.Date::toString method uses the shorter YYYY-MM-DD format used in SQL environments. That format also happens to comply with ISO 8601 standard as well, by the way.
In contrast, the output you report matches that of java.util.Date::toString.
java.time
The issue is moot. You are using terrible old date-time classes that were supplanted years ago by the java.time classes.
java.sql.Date is replaced by java.time.LocalDate, a date-only only value without a time-of-day and without a time zone. (FYI, java.sql.Date pretends to have no time-of-day or time zone but actually has both, as an awkward subclass of java.util.Date.)
java.util.Date is replaced by java.time.Instant. Both represent a moment in UTC, though Instant has a finer resolution of nanoseconds instead of milliseconds. (FYI, java.util.Date actually has a time zone buried deep, inaccessible without getter/setter methods, but used in equals etc. One of many poor design decisions in these legacy classes.)
Here is some code, counterparts to that seen above.
// Modern classes
System.out.println( "LocalDate.now(): " + LocalDate.now() ;
System.out.println( "Instant.now(): " + Instant.now() ) ;
System.out.println( "ZonedDateTime.now( … ): " + ZonedDateTime.now( ZoneId.of( "Africa/Tunis" ) ) ) ;
See this code run live at IdeOne.com.
LocalDate.now(): 2018-07-31
Instant.now(): 2018-07-31T22:57:27.763Z
ZonedDateTime.now( … ): 2018-07-31T23:57:27.904+01:00[Africa/Tunis]
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Related

How to format Oracle date and timestamp type values in Java?

I have date and timestamp type fields in oracle db, I need to retrieve these values and map them to my object field. Though I format the values I do not get the expected result. Here is the my code snippet.
import java.util.Date;
public class Operation{
private Date created;
private Date valueDate;
public Date getValueDate() {
return this.valueDate;
}
public void setValueDate(Date valueDate) {
this.valueDate = valueDate;
}
public Date getCreated() {
return this.valueDate;
}
public void setCreated(Date created) {
this.created= created;
}
}
//here starts code snippet to call db method
SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formatCreated = df1.format(result.getTimestamp(22)); //Input from db: 23-FEB-18 06.17.42.302680 PM
//OutputFormat 2018-02-23 18:17:42.000302
String formatValueDate = df2.format(result.getTimestamp(23));//Input from db:23.02.2018 18:17:42
//OutputFormat 2018-02-23 18:17:42
Operation op = new Operartion();
op.setCreated(df1.parse(formatCreated)) //Output Fri Feb 23 18:17:42 GMT+04:00 2018
op.setCreated(df1.parse(formatValuedate)) //Output Fri Feb 23 18:17:42 GMT+04:00 2018
Any help appreciated!
This has been covered many times already on Stack Overflow. Search before posting.
So briefly…
Use java.time
Use modern java.time classes, rather than the troublesome old legacy date-time classes such as Date/Calendar.
Use smart objects, not dumb strings
As of JDBC 4.2, exchange java.time objects directly with the database.
Use Instant for TIMESTAMP WITH TIME ZONE
Use LocalDateTime for TIMESTAMP WITHOUT TIME ZONE
Use LocalDate for DATE
Call PreparedStatement::setObject and ResultSet::getObject.
myPreparedStatement.setObject( … , instant ) ;
And…
Instant instant = myResultSet.getObject( … , Instant.class ) ;
Note that no strings were used at all.
//Input from db: 23-FEB-18 06.17.42.302680 PM
Incorrect. Your assumption is false. The database uses its own internally-defined binary format to store date-time values, not strings/text. Do not conflate date-time values with their textual representations. In other words, date-time values do not have a “format”.
Strings
Generate strings in standard ISO 8601 format by calling toString on the java.time objects.
String output = instant.toString() ;
For other formats, use DateTimeFormatter instead of SimpleDateFormat. Already covered well on Stack Overflow, so search.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Convert current date & time to equivalent GMT date & time

I used the below code where I've printed the modified GMT date in String & in Date format, it's giving me two different values.
Date initial = new Date();
DateFormat dateFormatter = DateFormat.getInstance();
dateFormatter.setTimeZone (TimeZone.getTimeZone("UTC"));
String gmtS = dateFormatter.format(initial);
Date gmt = dateFormatter.parse(gmtS);
System.out.println("Data type is Date = " + gmt);
System.out.println("Data type is String "+gmtS);
Output
gtm where value id of type Date = Thu Jul 03 23:15:00 EDT 2014
gmtS where value id of type String = 7/4/14 3:15 AM
But I want to see the value (7/4/14 3:15 AM) as a Date type.
Any help is really appreciated.
When you output a Date by calling toString() (which is what System.out.println("Data type is Date = " + gmt); does) you will get that Date according to the system time zone, because that is what Date.toString() returns.
Converts this Date object to a String of the form:
dow mon dd hh:mm:ss zzz yyyy
where:
...
zzz is the time zone (and may reflect daylight saving time). Standard time
zone abbreviations include those recognized by the method parse. If time
zone information is not available, then zzz is empty - that is, it
consists of no characters at all.
So, to get the output you expect use your dateFormatter to format it again.
String gmtS = dateFormatter.format(initial);
Date gmt = dateFormatter.parse(gmtS);
System.out.println("Data type is Date = " + dateFormatter.format(gmt));
tl;dr
Instant.now().toString()
2019-02-07T19:15:29.123456Z
Avoid legacy date-time classes
You are using date-time classes that are terribly troublesome, with many flaws in design.
First, you should know that java.util.Date represents a moment in UTC, always in UTC by definition. But its toString method tells a lie, dynamically applying the JVM’s current default time zone while generating the text representing the moment in the Date object.
java.time
The modern approach uses the java.time classes.
Instant
For a moment in UTC, use Instant. Like java.time.Date it represents a moment always in UTC (but with a finer resolution of nanoseconds versus milliseconds). Indeed, you can convert easily back-and-forth between Date and Instant by using new methods added to the old class.
Unlike toString on Date, the toString method on Instant always tells the truth. The method generates text in standard ISO 8601 format. The T in the middle separates the date portion from the time portion. The Z on the end is short for UTC and is pronounced “Zulu”.
Instant.now().toString(): 2019-01-23T12:34:56.123456789Z
OffsetDateTime
The Instant class is a basic building-block class in java.time, with limited functionality. If you want more flexible formatting, use the OffsetDateTime class with the offset set to UTC.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;
Or skip the Instant class.
OffsetDateTime odt = OffsetDateTime.now( ZoneOffset.UTC ) ;
To generate text representing the value of the OffsetDateTime object, use the DateTimeFormatter class. Search Stack Overflow as this has been covered many many times already.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Using setDate in PreparedStatement

In order to make our code more standard, we were asked to change all the places where we hardcoded our SQL variables to prepared statements and bind the variables instead.
I am however facing a problem with the setDate().
Here is the code:
DateFormat dateFormatYMD = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
DateFormat dateFormatMDY = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date now = new Date();
String vDateYMD = dateFormatYMD.format(now);
String vDateMDY = dateFormatMDY.format(now);
String vDateMDYSQL = vDateMDY ;
java.sql.Date date = new java.sql.Date(0000-00-00);
requestSQL = "INSERT INTO CREDIT_REQ_TITLE_ORDER (REQUEST_ID," +
" ORDER_DT, FOLLOWUP_DT) " + "values(?,?,?,)";
prs = conn.prepareStatement(requestSQL);
prs.setInt(1,new Integer(requestID));
prs.setDate(2,date.valueOf(vDateMDYSQL));
prs.setDate(3,date.valueOf(sqlFollowupDT));
I get this error when the SQL gets executed:
java.lang.IllegalArgumentException
at java.sql.Date.valueOf(Date.java:138)
at com.cmsi.eValuate.TAF.TAFModuleMain.CallTAF(TAFModuleMain.java:1211)
Should I use setString() instead with a to_date()?
❐ Using java.sql.Date
If your table has a column of type DATE:
java.lang.String
The method java.sql.Date.valueOf(java.lang.String) received a string representing a date in the format yyyy-[m]m-[d]d. e.g.:
ps.setDate(2, java.sql.Date.valueOf("2013-09-04"));
java.util.Date
Suppose you have a variable endDate of type java.util.Date, you make the conversion thus:
ps.setDate(2, new java.sql.Date(endDate.getTime());
Current
If you want to insert the current date:
ps.setDate(2, new java.sql.Date(System.currentTimeMillis()));
// Since Java 8
ps.setDate(2, java.sql.Date.valueOf(java.time.LocalDate.now()));
❐ Using java.sql.Timestamp
If your table has a column of type TIMESTAMP or DATETIME:
java.lang.String
The method java.sql.Timestamp.valueOf(java.lang.String) received a string representing a date in the format yyyy-[m]m-[d]d hh:mm:ss[.f...]. e.g.:
ps.setTimestamp(2, java.sql.Timestamp.valueOf("2013-09-04 13:30:00");
java.util.Date
Suppose you have a variable endDate of type java.util.Date, you make the conversion thus:
ps.setTimestamp(2, new java.sql.Timestamp(endDate.getTime()));
Current
If you require the current timestamp:
ps.setTimestamp(2, new java.sql.Timestamp(System.currentTimeMillis()));
// Since Java 8
ps.setTimestamp(2, java.sql.Timestamp.from(java.time.Instant.now()));
ps.setTimestamp(2, java.sql.Timestamp.valueOf(java.time.LocalDateTime.now()));
tl;dr
With JDBC 4.2 or later and java 8 or later:
myPreparedStatement.setObject( … , myLocalDate )
…and…
myResultSet.getObject( … , LocalDate.class )
Details
The Answer by Vargas is good about mentioning java.time types but refers only to converting to java.sql.Date. No need to convert if your driver is updated.
java.time
The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat. The Joda-Time team also advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
LocalDate
In java.time, the java.time.LocalDate class represents a date-only value without time-of-day and without time zone.
If using a JDBC driver compliant with JDBC 4.2 or later spec, no need to use the old java.sql.Date class. You can pass/fetch LocalDate objects directly to/from your database via PreparedStatement::setObject and ResultSet::getObject.
LocalDate localDate = LocalDate.now( ZoneId.of( "America/Montreal" ) );
myPreparedStatement.setObject( 1 , localDate );
…and…
LocalDate localDate = myResultSet.getObject( 1 , LocalDate.class );
Before JDBC 4.2, convert
If your driver cannot handle the java.time types directly, fall back to converting to java.sql types. But minimize their use, with your business logic using only java.time types.
New methods have been added to the old classes for conversion to/from java.time types. For java.sql.Date see the valueOf and toLocalDate methods.
java.sql.Date sqlDate = java.sql.Date.valueOf( localDate );
…and…
LocalDate localDate = sqlDate.toLocalDate();
Placeholder value
Be wary of using 0000-00-00 as a placeholder value as shown in your Question’s code. Not all databases and other software can handle going back that far in time. I suggest using something like the commonly-used Unix/Posix epoch reference date of 1970, 1970-01-01.
LocalDate EPOCH_DATE = LocalDate.ofEpochDay( 0 ); // 1970-01-01 is day 0 in Epoch counting.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
The docs explicitly says that java.sql.Date will throw:
IllegalArgumentException - if the date given is not in the JDBC date escape format (yyyy-[m]m-[d]d)
Also you shouldn't need to convert a date to a String then to a sql.date, this seems superfluous (and bug-prone!). Instead you could:
java.sql.Date sqlDate := new java.sql.Date(now.getTime());
prs.setDate(2, sqlDate);
prs.setDate(3, sqlDate);
The problem you're having is that you're passing incompatible formats from a formatted java.util.Date to construct an instance of java.sql.Date, which don't behave in the same way when using valueOf() since they use different formats.
I also can see that you're aiming to persist hours and minutes, and I think that you'd better change the data type to java.sql.Timestamp, which supports hours and minutes, along with changing your database field to DATETIME or similar (depending on your database vendor).
Anyways, if you want to change from java.util.Date to java.sql.Date, I suggest to use
java.util.Date date = Calendar.getInstance().getTime();
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
// ... more code here
prs.setDate(sqlDate);
If you want to add the current date into the database, I would avoid calculating the date in Java to begin with. Determining "now" on the Java (client) side leads to possible inconsistencies in the database if the client side is mis-configured, has the wrong time, wrong timezone, etc. Instead, the date can be set on the server side in a manner such as the following:
requestSQL = "INSERT INTO CREDIT_REQ_TITLE_ORDER (" +
"REQUEST_ID, ORDER_DT, FOLLOWUP_DT) " +
"VALUES(?, SYSDATE, SYSDATE + 30)";
...
prs.setInt(1, new Integer(requestID));
This way, only one bind parameter is required and the dates are calculated on the server side will be consistent. Even better would be to add an insert trigger to CREDIT_REQ_TITLE_ORDER and have the trigger insert the dates. That can help enforce consistency between different client apps (for example, someone trying to do a fix via sqlplus.
Not sure, but what I think you're looking for is to create a java.util.Date from a String, then convert that java.util.Date to a java.sql.Date.
try this:
private static java.sql.Date getCurrentDate(String date) {
java.util.Date today;
java.sql.Date rv = null;
try {
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
today = format.parse(date);
rv = new java.sql.Date(today.getTime());
System.out.println(rv.getTime());
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
} finally {
return rv;
}
}
Will return a java.sql.Date object for setDate();
The function above will print out a long value:
1375934400000

can we convert String formatted date dd/mm/yyyyy to Date type in same format?

I'm using struts2.x with jquery date picker.
I want to dispaly in the format dd/mm/yyyy. But from the database when fetching it is coming like yyyy-mm-dd.Then i converted it into the required format but the type is String. So next i Converted it to Date type. But the format is changed.
Date getRiskCommDate()
{
String fString = null;
System.out.println("Coming Date from DB"+riskCommDate);
if(riskCommDate!=null)
{
SimpleDateFormat format = new SimpleDateFormat();
format.applyPattern("dd/MM/yyyy");
fString = format.format(riskCommDate);
}
System.out.println("Formated Date in String Form "+fString);
Date d = new Date(fString);
System.out.println("Formated Date in Date form Date "+d);
return d;
}
Output :
Coming Date from DB 2012-07-04
Formated Date in String Form 04/07/2012
Formated Date in Date form Date Sat Apr 07 00:00:00 IST 2012
Any idea is highly appreciated.
The java.util.Date class does not have any property to hold a format.
To display the value of the Date in a custom format, call the format method on SimpleDateFormat.
When you do this:
System.out.println(dateInstance)
…you are simply calling the toString() on the Date. That method returns the date in fixed format in String version.
Based on the comments
If you anyhow wants the custom format with date instance then you can either create a custom class wrapping date instance
class MyDate{
private Date date;
//provide appropriate accessor
//override toString() method to support required output
}
or extend Date
class MyDate extends Date{
//override toString() method to support required output
#Override
public String toString(){
//convert `this` to String with required format with the help of `SimpleDateFormat`
}
}
Date prints a format based on the Locale. It doesn't "remember" the format you gave it want you constructed it. Only Strings have a particular format, so if you need that, keep it as a String.
java.time
The old troublesome date-time libraries bundled with early Java have been supplanted by the java.time framework built into Java 8 and later. For Java 6 & 7, use the back-port, ThreeTen-Backport, and for Android the adaption thereof, ThreeTenABP. Avoid using the old java.util.Date/.Calendar and such.
LocalDate
The java.time classes include LocalDate for a date-only value without time-of-day and without time zone.
java.sql.Date
Hopefully JDBC drivers will be updated to deal directly with java.time types. Until then, use java.sql types for moving data in/out of database. The old java.sql classes have new to… and valueOf methods for conversion with java.time. Our interest here is in java.sql.Date.
LocalDate localDate = myJavaSqlDate.toLocalDate();
You can go the other direction, for submission to the database.
java.sql.Date myJavaSqlDate = java.sql.Date.valueOf( localDate );
Generate String
None of the discussed date classes (java.util.Date, java.sql.Date, java.time.LocalDate) have any “format”. Only textual representations of their values have a format. If you need a String, those classes can generate a String object for you. But do not confuse that String object with a date-time object as they are entirely separate and distinct.
The toString method on LocalDate use standard ISO 8601 format such as 2012-07-04 (meaning July 4, 2012).
String outputIso8601 = localDate.toString();
For other formats, use a DateTimeFormatter. Many other Questions and Answers on Stack Overflow have more discussion.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd/MM/yyyy" );
String output = localDate.format( formatter ); // Generates a textual representation of the object’s date-only value.
Better yet, let java.time localize for you.
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT );
formatter = formatter.withLocale( Locale.CANADA_FRENCH ); // or Locale.US, and so on.
String output = localDate.format( formatter );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Java date is not preserving milliseconds in conversion with simple date format

I'm trying to convert the following string "2012-04-13 04:08:42.794" to a date type:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
Date convertedDate;
try {
convertedDate = dateFormat.parse(dateString);
System.out.println(" in utils: "+convertedDate.toString());
} catch (ParseException e) {
e.printStackTrace();
return null;
}
//----------------- i think this is the problem
java.sql.Date sqlDate = new java.sql.Date(convertedDate.getTime());
System.out.println("sql: "+sqlDate.toString());
return sqlDate;
But this is printing the following:
in utils: Fri Apr 13 04:08:42 PDT 2012
How can I get this date to preserve the milliseconds?
The convertedDate object does in fact contain the millisecond information. The issue here is that the toString() method format does not print milliseconds.
Do
System.out.println(" in utils: " + dateFormat.format(convertedDate));
You can also check if the ms are set with
System.out.println("millis: " + convertedDate.getTime());
He's my go at it (trying to keep the same code style as yours) :
import java.util.*;
import java.text.*;
public class main {
public static void main(String[] args)throws Exception {
long yourmilliseconds = 1119193190;
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm:ss.SSS");
Date resultdate = new Date(yourmilliseconds);
System.out.println(sdf.format(resultdate)); }
}
Output :
Jan 13,1970 17:53:13.190
Regards, Erwald
Instead of printing using toString() you can make your own printing method, so it prints the information you want specifically. Also note that most of the Date class is deprecated - look at http://docs.oracle.com/javase/6/docs/api/java/util/Date.html
Calendar now = Calendar.getInstance();
System.out.println("Current milliseconds since Jan 1, 1970 are :"
+ now.getTimeInMillis());
just use java.util.Calendar http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html
tl;dr
myPreparedStatetment.setObject(
… ,
LocalDateTime.parse(
"2012-04-13 04:08:42.794".replace( " " , "T" )
)
)
Details
The Answer by SJuan76 is correct: You are being fooled by the poorly-designed output of the Date::toString method. Instead, use java.time classes.
java.time
The modern approach uses the java.time classes that supplanted the troublesome old date-time classes such as Date/Calendar.
First convert your input string to fully comply with the ISO 8601 standard. Replace the SPACE in the middle with a T.
String input = "2012-04-13 04:08:42.794".replace( " " , "T" ) ;
Parse as a LocalDateTime since your input lacks an indicator of offset-from-UTC or time zone.
LocalDateTime ldt = LocalDateTime.parse( input ) ;
ldt.toString(): 2012-04-13T04:08:42.794
SQL
Avoid the date-time related java.sql classes. They too are supplanted by the java.time classes. As of JDBC 4.2, you can directly exchange java.time objects with your database. So you can forget all about the java.sql.Date class and its terrible hacked design.
myPreparedStatement.setObject( … , ldt ) ;
And…
LocalDateTime ldt = myResultSet.getObject( … , LocalDateTime.class ) ;
Morals
Moral of the story # 1: Use smart objects, not dumb strings.
Moral of the story # 2: Use only java.time objects. Avoid legacy date-time classes.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Categories