This question already has answers here:
Parsing String into mysql Date [duplicate]
(4 answers)
Closed 5 years ago.
I'm facing some problems in Eclipse with dates. I'm showing a date in a TextField with the format
dd/MM/yyyy
and I need to get the text from this textfield and parse it as a date to insert it in my database into a column of type DATE I'm using MySQL and it accepts dates as
yyyy-MM-dd
I tried really many options, both with LocalDate or the older Date, but didn't find a solution. Can someone please help? Thank you!
Prior Java 8 approach
Firstly, after retrieving your string from your TextField, you should parse it to java.util.Date:
String text = textField.getText();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date textFieldAsDate = null;
try {
textFieldAsDate = sdf.parse(text);
} catch (ParseException pe) {
// deal with ParseException
}
Afterwards, you can convert your java.util.Date into a java.sql.Date, to store it into your MySQL database, like this:
sdf = new SimpleDateFormat("yyyy-MM-dd");
java.sql.Date date = java.sql.Date.valueOf(sdf.format(textFieldAsDate));
Java 8 approach
As mentioned by #BasilBourque, the Java date and time mechanism was provided by java.util.Date, java.util.Calendar, and java.util.TimeZone classes which are now legacy.
Therefore, in order to accomplish using Java 8 what was previously mentioned, one can do the following:
String text = textField.getText();
java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern("dd/MM/yyyy");
java.time.LocalDate textFieldAsDate = java.time.LocalDate.parse(text, formatter);
Afterwards, in order to convert the LocalDate into a java.sql.Date, to store it into your MySQL database, it's possible to do the following:
java.sql.Date sqlDate = java.sql.Date.valueOf(textFieldAsDate);
You want to use the SimpleDateFormat class
Once you have extracted it from the TextField, you can use this:
String extractedDate = "dd/MM/yyyy" // Whatever date you've extracted
Date date = new SimpleDateFormat("dd/MM/yyyy").parse(extractedDate);
String correctDate = new SimpleDateFormat("yyyy-MM-dd").format(date);
System.out.println(correctDate); // "yyyy-MM-dd" for whatever date was extracted
Try this:
SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
Date date = df.parse("2016-03-05");
java.time
The other Answers are correct but use outdated classes. The old date-time classes such as java.util.Date/.Calendar have proven to be poorly designed, confusing, and troublesome. Avoid them. They have been supplanted by the java.time framework built into Java 8 and later.
Define a pattern by which to parse your input string.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd/MM/yyyy" );
Parse the input string as a LocalDate object, representing a date-only value without time-of-day nor time zone.
LocalDate localDate = LocalDate.parse( "23/01/2016" , formatter );
Someday the JDBC drivers will be updated to work directly with the java.time types. But until then we must convert to the java.sql types for transferring data to/from the database.
java.sql.Date sqlDate = java.sql.Date.valueOf( localDate );
Then use a PreparedStatement, calling setDate and passing your sqlDate to write the value into the database.
To retrieve from the database, call getDate. Immediately convert to java.time by calling java.sql.Date::toLocalDate. Minimize your use of the java.sql types. Do your business logic in java.time.
If your JDBC driver complies with JDBC 4.2 and later, you can skip the java.sql types and use the java.time types directly.
PreparedStatement::setObjectmyPrepStmt.setObject( … , myLocalDate )
ResultSet::getObjectLocalDate ld = myResultSet.getObject( … , LocalDate.class );
This Question is really a duplicate. Search Stack Overflow for many more examples.
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.
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
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
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
This question already has answers here:
Calendar returns date in wrong time zone
(5 answers)
Getting the current time millis from device and converting it into a new date with different timezone [duplicate]
(2 answers)
DateFormat parse - not return date in UTC
(1 answer)
Closed 4 years ago.
We are converting database date into required user timezone. But if we format using jodatime in string format we are getting correct date and if we parse string to get date object we are getting wrong time. Here is my code. I tried jodatime parser and java date
public class Test {
public static void main(String[] args) {
String dateF = "01/19/2019 at 07:35 PM (UTC)";
String dateFormat = "MM/dd/yyyy 'at' hh:mm a (zzz)";
long time = 1603305000;
String timeZone = "Etc/UTC";
Locale locale=new Locale("en", "US");
DateTimeFormatter dateFormatter = null;
if (locale.equals(Locale.FRENCH)) {
dateFormatter = DateTimeFormat.forPattern(dateFormat).withLocale(locale);
} else {
dateFormatter = DateTimeFormat.forPattern(dateFormat).withLocale(null);
}
if (true) {
dateFormatter = dateFormatter.withZone(DateTimeZone.forID(timeZone));
}
// Old Logic using Java Time
DateFormat format3 = new SimpleDateFormat(dateFormat, locale);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(time);
if(true)
format3.setTimeZone(TimeZone.getTimeZone(timeZone));
DateTime jodatime = new DateTime(time);
try {
System.out.println(dateFormatter.print(jodatime));
System.out.println("timezone converted Date : " + format3.parse(dateFormatter.print(jodatime)));
System.out.println("dateFormatter.parseDateTime converted Date : " + dateFormatter.parseDateTime(dateFormatter.print(jodatime)).toDate());
} catch (Exception e) {
System.out.println(e);
}
}
}
Correct date in Formatted string 01/19/1970 at 01:21 PM (UTC)
We are getting a wrong result after parsing
timezone converted Date : Mon Jan 19 18:51:00 IST 1970
dateFormatter.parseDateTime converted Date : Mon Jan 19 18:51:00 IST 1970
Correct date in Formatted Date : Mon Jan 19 01:21:00 UTC 1970
Avoid legacy date-time classes
You are using terrible old classes bundled with the earliest versions of Java. These have been supplanted entirely by the modern java.time classes.
You are also apparently mixing those legacy classes with classes from the Joda-Time library. Firstly, that mixing is ill-advised. Secondly, Joda-Time is now in maintenance-mode, with its creators advising migration to java.time. Actually, both Joda-Time and java.time projects are led by the same man, Stephen Colebourne, with the first project having been the inspiration and education for the second.
Smart objects, not dumb strings
We are converting database date
Then avoid all the string manipulations you are doing.
As of JDBC 4.2, you can directly exchange java.time objects with your database. For a moment, meaning a column of a type akin to the SQL-standard TIMESTAMP WITH TIME ZONE, use OffsetDateTime class.
myPreparedStatement.setObject( … , myOffsetDateTime ) ;
…and…
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
Most databases store moments in UTC. You may want to adjust into a time zone for presentation to users. Apply a ZoneId to get a ZonedDateTime object.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;
Generate text in a certain format by using DateTimeFormatter object. Either specify a custom formatting pattern or automatically localize by calling ofLocalized… methods.
All of this has been covered many many many times on Stack Overflow already. Search to learn more.
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.
I want to compare two dates fetched from a SQL query to know which one is greater. Date format in the sql is
2018-11-22 11:12:38.291647
I tried using
java.util.Date sqlDate=new java.util.Date(resultset.getDate().getTime());
But it keeps on asking to change the datatype to int.
I also tried using
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
java.util.Date d=df.format(/*date String*/);
But this also does not work. it keeps on asking to change the datatype of d to String.
You can order the result of a query in SQL with the ORDER BY command. If you want the "biggest" date, you should order the query descending: ORDER BY DESC.
This way you can get the biggest date from the ResultSet object holding the result of your query by simply extracting the first element.
First, convert in Date objects:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.sss");
Date date = format.parse(yourDate);
and then compare them using Date.after or Date.before
This type of format is comparable in java by comparing the strings, so you don't need any conversion:
String date1 = "2018-11-22 11:12:38.291647";
String date2 = "2018-11-23 10:11:00.090600";
int result = date1.compareTo(date2);
System.out.println(result);
will print
-1
because date2 is "greater" than date1.
if date1 is "greater" than date2 the result is 1 and
if date1 is "equal" to date2 the result is 0
No “format” in database
Date format in the sql is 2018-11-22 11:12:38.291647
No, it is not.
Date-time values stored in date-time types have no “format”. Formats are for strings. A database stores a date-time value by its own internally-defined data structure. The details of that data structure is none of our business.
Smart objects, not dumb strings
Exchange date-time objects of a date-time class with a database for values stored in a date-time column.
As of JDBC 4.2, we can exchange java.time objects with the database. No need to ever again use those terrible legacy classes such as java.sql.Timestamp, java.sql.Date, java.util.Date, and java.util.Calendar.
For a moment, in the database use a column of a type akin to the SQL-standard TIMESTAMP WITH TIME ZONE.
OffsetDateTime
For such a column, pass a OffsetDateTime object to your prepared statement. Usually best to work in UTC.
Instant instant = Instant.parse( "2018-11-22T11:12:38.291647Z" ) ; // `Z` on the end means UTC. Pronounced “Zulu”.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;
myPreparedStatement.setObject( … , odt ) ;
Retrieval.
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
Compare
Compare OffsetDateTime objects using isBefore, isAfter, and isEqual.
boolean aIsBeforeThanB = odtA.isBefore( odtB );
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.
I am trying to parse the date according to the following code but getting exception. Below is the code -
public class DateTest {
public static void main(String args []) {
String start = "23-Jan-2017";
DateFormat dateFormatTripStartDate = new SimpleDateFormat("dd-MMM-yyyy hh:mm a");
try {
Date parsedDate = dateFormatTripStartDate.parse(start);
System.out.println(parsedDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Exception :
java.text.ParseException: Unparseable date: "23-Jan-2017"
at java.text.DateFormat.parse(DateFormat.java:357)
at DateTest.main(DateTest.java:18)
Kindly help me identify the problem. Thanks.
Remove the time part in your pattern:
DateFormat dateFormatTripStartDate = new SimpleDateFormat("dd-MMM-yyyy");
tl;dr
LocalDate.parse(
"23-Jan-2017" ,
DateTimeFormatter.ofPattern( "dd-MMM-uuuu" , Locale.US )
)
Using java.time
Other Answers are correct about formatting pattern mismatching input data. But both the Question and other Answers are outdated.
The modern way is with java.time classes that supplant the troublesome old date-time classes.
The LocalDate class represents a date-only value without time-of-day and without time zone.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MMM-uuuu" , Locale.US );
LocalDate ld = LocalDate.parse( "23-Jan-2017" , f );
ld.toString(): 2017-01-23
Specify the Locale as that determines the human language used to translate the name of the month. If omitted the JVM’s current default Locale is used implicitly. That default can be changed at any moment by any code in any thread of any app within the JVM, so do not rely upon it.
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.
Where to obtain the java.time classes?
Java SE 8 and 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 SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
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, andfz more.
First of all, the answer from kamehl23 is correct. Your parsed string may not be missing any parst that are specified in format and thus you will need to modify your format to DateFormat dateFormatTripStartDate = new SimpleDateFormat("dd-MMM-yyyy"); However just to add few more interesting options: Remember that SimpleDateFormat is not thread safe and in general not recommended. Sensible pre Java 8 options are Apache FastDateFormat and joda-time package. Both have some problems but certainly by far better then SimpleDateFormat (Joda-time package is very popular). In Java 8 a new date and time hanling was introduced with package java.time.format It takes time to adjust to it but it works wonderful and resolves many problems that existed in that area. See class DateTimeFormatter.And finally, I once had to write a utility that can take a String in any format and attempt to parse it to Date if possible. I wrote an article that describes how I implemented that Utility. I wrote it in Java 8, but the idea could be implemented in any version. See Java 8 java.time package: parsing any string to date
You are using pattern "dd-MMM-yyyy hh:mm a". But in actual "hh:mm a" part is not present in the "23-Jan-2017" value. Because of this parse function is not able to parse the String date.
So change your pattern to "dd-MMM-yyyy" which matches your date string. This will remove the exception you are getting.
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
I have a CSV file I'm trying to import using java. File with date column and dates in different formats I'd like to parse dates suitable for myqsl.
My code as:
CSVFormat format = CSVFormat.RFC4180.withHeader().withDelimiter(',');
CSVParser parsernew =CSVParser(File, format)
List<CSVRecord> csvRecordList = parser.getRecords();
String cellvalue=csvRecordList.get(0);
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = dateFormat .parse(cellvalue);
I'm trying to parse date column value but got Exception
java.text.ParseException: Unparseable date:
date column values as likes
10/31/2014
12/13/2013
2001-02-04
7/27/2001
2001-02-04
5/15/2008
Is there any way to parse different date formats and date format changes run time time how to handle that..
in excel
Thanks!
Fix the source of data
Firstly, you should educate the publisher of this data about using only standard ISO 8601 formats when serializing date-time values as text. For a date-only without time-of-day and without time zone, that would be YYYY-MM-DD.
Attempt parsing each of the two known formats
Fortunately, your example data shows only two formats: the standard YYYY-MM-DD format, and M/D/YYYY.
So try parsing with a pair of formatters, one for each case. If both fail, throw an exception to alert you to the publisher’s unfortunate use of even more formats.
java.time
Use only java.time classes. Never use the terrible old date-time classes such as Date and DateFormat. Those legacy classes were supplanted years ago with the adoption of JSR 310 in Java 8 and later.
DateTimeFormatter
Define the pair of formatters. The standard one is already defined as a constant: DateTimeFormatter.ISO_LOCAL_DATE. Define the other.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "M/d/uuuu" ) ;
Get your input string in your code using the Apache Commons CSV library. But your code looks wrong in the Question. You need to add a loop for each of the CSVRecord objects in your list. Then extract each column from each row represented by that object.
CSVRecord record = = csvRecordList.get( i ) ; // Fetch nth object from list.
String cellvalue = csvRecordList.get( 0 ) ; // Extract each column/cell from each row/object. Must use annoying zero-based index counting.
Catch DateTimeParseException
Attempt to parse the input using each of the two formatters using LocalDate.parse. Catch the DateTimeParseException.
LocalDate ld = null;
if( Objects.isNull( ld ) ) {
try {
ld = LocalDate.parse( cellvalue , DateTimeFormatter.ISO_LOCAL_DATE ) ;
} catch ( DateTimeParseException e ) {
// Swallow this particular exception in this particular case.
}
}
if( Objects.isNull( ld ) ) {
try {
ld = LocalDate.parse( cellvalue , f ) ;
} catch ( DateTimeParseException e ) {
// Swallow this particular exception in this particular case.
}
}
if( Objects.isNull( ld ) ) {
// Yikes! Failing all parsing attempts above means we encountered an unexpected format.
// FIXME: Handle this error scenario.
}
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.
You can use SimpleFlatMapper to define different date formats.
As an example:
CsvParser.mapWith(CsvMapperFactory.newInstance()
.addColumnProperty(k -> k.getName().toLowerCase().contains("date"), new DateFormatProperty("dd/MM/yyyy"))
.addColumnProperty(k -> k.getName().toLowerCase().contains("date"), new DateFormatProperty("dd-MM-yyyy"))
.newMapper(Trade.class))
.stream(reader).collect(toList());