How to convert java.util.Date to java.sql.Date? - java

I am trying to use a java.util.Date as input and then creating a query with it - so I need a java.sql.Date.
I was surprised to find that it couldn't do the conversion implicitly or explicitly - but I don't even know how I would do this, as the Java API is still fairly new to me.

Nevermind....
public class MainClass {
public static void main(String[] args) {
java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
System.out.println("utilDate:" + utilDate);
System.out.println("sqlDate:" + sqlDate);
}
}
explains it. The link is http://www.java2s.com/Tutorial/Java/0040__Data-Type/ConvertfromajavautilDateObjecttoajavasqlDateObject.htm

tl;dr
How to convert java.util.Date to java.sql.Date?
Don’t.
Both Date classes are outmoded. Sun, Oracle, and the JCP community gave up on those legacy date-time classes years ago with the unanimous adoption of JSR 310 defining the java.time classes.
Use java.time classes instead of legacy java.util.Date & java.sql.Date with JDBC 4.2 or later.
Convert to/from java.time if inter-operating with code not yet updated to java.time.
Legacy
Modern
Conversion
java.util.Date
java.time.Instant
java.util.Date.toInstant()java.util.Date.from( Instant )
java.sql.Date
java.time.LocalDate
java.sql.Date.toLocalDate()java.sql.Date.valueOf( LocalDate )
Example query with PreparedStatement.
myPreparedStatement.setObject(
… , // Specify the ordinal number of which argument in SQL statement.
myJavaUtilDate.toInstant() // Convert from legacy class `java.util.Date` (a moment in UTC) to a modern `java.time.Instant` (a moment in UTC).
.atZone( ZoneId.of( "Africa/Tunis" ) ) // Adjust from UTC to a particular time zone, to determine a date. Instantiating a `ZonedDateTime`.
.toLocalDate() // Extract a date-only `java.time.LocalDate` object from the date-time `ZonedDateTime` object.
)
Replacements:
Instant instead of java.util.DateBoth represent a moment in UTC. but now with nanoseconds instead of milliseconds.
LocalDate instead of java.sql.DateBoth represent a date-only value without a time of day and without a time zone.
Details
If you are trying to work with date-only values (no time-of-day, no time zone), use the LocalDate class rather than java.util.Date.
java.time
In Java 8 and later, the troublesome old date-time classes bundled with early versions of Java have been supplanted by the new java.time package. See Oracle Tutorial. Much of the functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
A SQL data type DATE is meant to be date-only, with no time-of-day and no time zone. Java never had precisely such a class† until java.time.LocalDate in Java 8. Let's create such a value by getting today's date according to a particular time zone (time zone is important in determining a date as a new day dawns earlier in Paris than in Montréal, for example).
LocalDate todayLocalDate = LocalDate.now( ZoneId.of( "America/Montreal" ) ); // Use proper "continent/region" time zone names; never use 3-4 letter codes like "EST" or "IST".
At this point, we may be done. If your JDBC driver complies with JDBC 4.2 spec, you should be able to pass a LocalDate via setObject on a PreparedStatement to store into a SQL DATE field.
myPreparedStatement.setObject( 1 , localDate );
Likewise, use ResultSet::getObject to fetch from a SQL DATE column to a Java LocalDate object. Specifying the class in the second argument makes your code type-safe.
LocalDate localDate = ResultSet.getObject( 1 , LocalDate.class );
In other words, this entire Question is irrelevant under JDBC 4.2 or later.
If your JDBC driver does not perform in this manner, you need to fall back to converting to the java.sql types.
Convert to java.sql.Date
To convert, use new methods added to the old date-time classes. We can call java.sql.Date.valueOf(…) to convert a LocalDate.
java.sql.Date sqlDate = java.sql.Date.valueOf( todayLocalDate );
And going the other direction.
LocalDate localDate = sqlDate.toLocalDate();
Converting from java.util.Date
While you should avoid using the old date-time classes, you may be forced to when working with existing code. If so, you can convert to/from java.time.
Go through the Instant class, which represents a moment on the timeline in UTC. An Instant is similar in idea to a java.util.Date. But note that Instant has a resolution up to nanoseconds while java.util.Date has only milliseconds resolution.
To convert, use new methods added to the old classes. For example, java.util.Date.from( Instant ) and java.util.Date::toInstant.
Instant instant = myUtilDate.toInstant();
To determine a date, we need the context of a time zone. For any given moment, the date varies around the globe by time zone. Apply a ZoneId to get a ZonedDateTime.
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant , zoneId );
LocalDate localDate = zdt.toLocalDate();
† The java.sql.Date class pretends to be date-only without a time-of-day but actually does a time-of-day, adjusted to a midnight time. Confusing? Yes, the old date-time classes are a mess.
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.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
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. Hibernate 5 & JPA 2.2 support java.time.
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 brought 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 (26+) bundle implementations of the java.time classes.
For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. 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.

With the other answer you may have troubles with the time info (compare the dates with unexpected results!)
I suggest:
java.util.Calendar cal = Calendar.getInstance();
java.util.Date utilDate = new java.util.Date(); // your util date
cal.setTime(utilDate);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
java.sql.Date sqlDate = new java.sql.Date(cal.getTime().getTime()); // your sql date
System.out.println("utilDate:" + utilDate);
System.out.println("sqlDate:" + sqlDate);

This function will return a converted SQL date from java date object.
public java.sql.Date convertJavaDateToSqlDate(java.util.Date date) {
return new java.sql.Date(date.getTime());
}

Converting java.util.Date to java.sql.Date will lose hours, minutes and seconds. So if it is possible, I suggest you to use java.sql.Timestamp like this:
prepareStatement.setTimestamp(1, new Timestamp(utilDate.getTime()));
For more info, you can check this question.

In my case of picking date from JXDatePicker (java calender) and getting it stored in database as SQL Date type, below works fine ..
java.sql.Date date = new java.sql.Date(pickedDate.getDate().getTime());
where pickedDate is object of JXDatePicker

This function will return a converted SQL date from java date object.
public static java.sql.Date convertFromJAVADateToSQLDate(
java.util.Date javaDate) {
java.sql.Date sqlDate = null;
if (javaDate != null) {
sqlDate = new Date(javaDate.getTime());
}
return sqlDate;
}

Format your java.util.Date first. Then use the formatted date to get the date in java.sql.Date
java.util.Date utilDate = "Your date"
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
final String stringDate= dateFormat.format(utilDate);
final java.sql.Date sqlDate= java.sql.Date.valueOf(stringDate);

Here the example of converting Util Date to Sql date and ya this is one example what i am using in my project might be helpful to you too.
java.util.Date utilStartDate = table_Login.getDob();(orwhat ever date your give form obj)
java.sql.Date sqlStartDate = new java.sql.Date(utilStartDate.getTime());(converting date)

I am a novice: after much running around this worked. Thought might be useful
String bufDt = bDOB.getText(); //data from form
DateFormat dF = new SimpleDateFormat("dd-MM-yyyy"); //data in form is in this format
Date bbdt = (Date)dF.parse(bufDt); // string data is converted into java util date
DateFormat dsF = new SimpleDateFormat("yyyy-MM-dd"); //converted date is reformatted for conversion to sql.date
String ndt = dsF.format(bbdt); // java util date is converted to compatible java sql date
java.sql.Date sqlDate= java.sql.Date.valueOf(ndt); // finally data from the form is convered to java sql. date for placing in database

Method for comparing 2 dates (util.date or sql.date)
public static boolean isSameDay(Date a, Date b) {
Calendar calA = new GregorianCalendar();
calA.setTime(a);
Calendar calB = new GregorianCalendar();
calB.setTime(b);
final int yearA = calA.get(Calendar.YEAR);
final int monthA = calA.get(Calendar.MONTH);
final int dayA = calA.get(Calendar.DAY_OF_YEAR);
final int yearB = calB.get(Calendar.YEAR);
final int monthB = calB.get(Calendar.MONTH);
final int dayB = calB.get(Calendar.DAY_OF_YEAR);
return yearA == yearB && monthA == monthB && dayA == dayB;
}

try with this
public static String toMysqlDateStr(Date date) {
String dateForMySql = "";
if (date == null) {
dateForMySql = null;
} else {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateForMySql = sdf.format(date);
}
return dateForMySql;
}

I think the best way to convert is:
static java.sql.Timestamp SQLDateTime(Long utilDate) {
return new java.sql.Timestamp(utilDate);
}
Date date = new Date();
java.sql.Timestamp dt = SQLDateTime(date.getTime());
If you want to insert the dt variable into an SQL table you can do:
insert into table (expireAt) values ('"+dt+"');

i am using the following code please try it out
DateFormat fm= new SimpleDateFormatter();
specify the format of the date you want
for example "DD-MM_YYYY" or 'YYYY-mm-dd' then use the java Date datatype as
fm.format("object of java.util.date");
then it will parse your date

You can use this method to convert util date to sql date,
DateUtilities.convertUtilDateToSql(java.util.Date)

I was trying the following coding that worked fine.
java.util.Date utilDate = new java.util.Date(); java.sql.Date
sqlDate = new java.sql.Date(utilDate);

If you are usgin Mysql a date column can be passed a String representation of this date
so i using the DateFormatter Class to format it and then set it as a String in the sql statement or prepared statement
here is the code illustration:
private String converUtilDateToSqlDate(java.util.Date utilDate) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String sqlDate = sdf.format(utilDate);
return sqlDate;
}
String date = converUtilDateToSqlDate(otherTransaction.getTransDate());
//then pass this date in you sql statement

Related

Json response to postgresql datetime conversion Java postgresql

I am getting the JSON responses for the Date time field as follows:
/Date(1534291200000)/ and PT12H18M02S
SELECT CAST('ClearingDate' AS TIMESTAMP) from testdata;
On using CAST functions or to_timestamp I am getting the following error:
ERROR: invalid input syntax for type timestamp: "/Date(1534291200000)/"
SQL state: 22007
How can I convert this to timestamp using postgresql? If not postgresql is there a way to do so in Java?
The solution to directly convert it in PostgreSQL:
to_timestamp(CAST(SUBSTRING (CAST(Clearingdate AS varchar), 9, 10) AS NUMERIC))
from date_test;
I finally figured it out. Thanks a lot for all your inputs.
use timestamp (import java.sql.Timestamp)
String fromJson = "/Date(1534291200000)/";
String ts = fromJson.substring(6, fromJson.length()-2);
Long tsInMillisSec = Long.parseLong(ts);
Timestamp ts = new Timestamp(tsInMillisSec);
Sorry, I don’t know how to do this in PostgreSQL. In Java:
String timestampString = "/Date(1534291200000)/";
String millisString = timestampString.replaceFirst("^/Date\\((\\d+)\\)/$", "$1");
Instant inst = Instant.ofEpochMilli(Long.parseLong(millisString));
System.out.println(inst);
Output is
2018-08-15T00:00:00Z
I am using a regular expression for validating the syntax of the string and taking out just the substring of digits. This number denoted milliseconds since the epoch. The Instant class from java.time, the modern Java date and time API, is the correct one to use for a timestamp (forget about the outdated Timestamp class, we don’t need it anymore).
If you need to store this back into PostgreSQL:
PreparedStatement stmt = yourConnection.prepareStatement(
"insert into your_table(your_timestamp_column) values (?);");
stmt.setObject(1, inst);
Please modify to your database design and situation.
Link: Oracle tutorial: Date Time explaining how to use java.time.
java.time
The date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.
For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7.
If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Instant#ofEpochMilli
The key here is to get an object of Instant out of the milliseconds in the given string. Once you have Instant, you can convert it to other java.time types e.g. ZonedDateTime or even to the legacy java.util.Date.
A note on the regex, \D+: \D specifies a non-digit while + specifies its one or more occurrence(s).
Demo:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String text = "/Date(1534291200000)/";
// Replace all non-digits i.e. \D+ with a blank string
Instant instant = Instant.ofEpochMilli(Long.parseLong(text.replaceAll("\\D+", "")));
System.out.println(instant);
// Now you can convert Instant to other java.time types e.g. ZonedDateTime
// ZoneId.systemDefault() returns the time-zone of the JVM. Replace it with the
// desired time-zone e.g. ZoneId.of("Europe/London")
ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
// Print the default format i.e. the value of zdt#toString
System.out.println(zdt);
// A custom format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE MMMM dd HH:mm:ss uuuu", Locale.ENGLISH);
String strDateTimeFormatted = zdt.format(dtf);
System.out.println(strDateTimeFormatted);
}
}
Output:
2018-08-15T00:00:00Z
2018-08-15T01:00+01:00[Europe/London]
Wed August 15 01:00:00 2018
How to get java.util.Date from an Instant?
You should avoid using java.util.Date but for whatsoever purpose, if you want to get java.util.Date, all you have to do is to use Date#from as shown below:
Date date = Date.from(instant);
What about PT12H18M02S?
You can parse it to java.time.Duration which is modelled on ISO-8601 standards and was introduced with Java-8 as part of JSR-310 implementation.
If you have gone through the above links, you might have already learnt that PT12H18M02S specifies a duration of 12 hours 18 minutes 2 seconds which you add to a date-time object (e.g. zdt obtained above) to get a new date-time.
Duration duration = Duration.parse("PT12H18M02S");
ZonedDateTime zdtUpdated = zdt.plus(duration);
System.out.println(zdtUpdated);
Output:
2018-08-15T13:18:02+01:00[Europe/London]
Learn about the modern date-time API from Trail: Date Time.
How to use java.time types with JDBC?
The PostgreSQL™ JDBC driver implements native support for the Java 8 Date and Time API (JSR-310) using JDBC 4.2.
Note that ZonedDateTime, Instant and OffsetTime / TIME [ WITHOUT TIMEZONE ] are not supported. Also, note that all OffsetDateTime instances will have to be in UTC (have offset 0). This is because the backend stores them as UTC.
OffsetDateTime odt = zdt.withZoneSameInstant(ZoneOffset.UTC).toOffsetDateTime();
PreparedStatement st = conn.prepareStatement("INSERT INTO mytable (columnfoo) VALUES (?)");
st.setObject(1, odt);
st.executeUpdate();
st.close();
This might work:
select cast(cast('{"dtJson":"2020-10-23 13:40:54"}'::json->'dtJson' as varchar) as timestamp);

Select by Date range of dates [duplicate]

I am trying to use a java.util.Date as input and then creating a query with it - so I need a java.sql.Date.
I was surprised to find that it couldn't do the conversion implicitly or explicitly - but I don't even know how I would do this, as the Java API is still fairly new to me.
Nevermind....
public class MainClass {
public static void main(String[] args) {
java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
System.out.println("utilDate:" + utilDate);
System.out.println("sqlDate:" + sqlDate);
}
}
explains it. The link is http://www.java2s.com/Tutorial/Java/0040__Data-Type/ConvertfromajavautilDateObjecttoajavasqlDateObject.htm
tl;dr
How to convert java.util.Date to java.sql.Date?
Don’t.
Both Date classes are outmoded. Sun, Oracle, and the JCP community gave up on those legacy date-time classes years ago with the unanimous adoption of JSR 310 defining the java.time classes.
Use java.time classes instead of legacy java.util.Date & java.sql.Date with JDBC 4.2 or later.
Convert to/from java.time if inter-operating with code not yet updated to java.time.
Legacy
Modern
Conversion
java.util.Date
java.time.Instant
java.util.Date.toInstant()java.util.Date.from( Instant )
java.sql.Date
java.time.LocalDate
java.sql.Date.toLocalDate()java.sql.Date.valueOf( LocalDate )
Example query with PreparedStatement.
myPreparedStatement.setObject(
… , // Specify the ordinal number of which argument in SQL statement.
myJavaUtilDate.toInstant() // Convert from legacy class `java.util.Date` (a moment in UTC) to a modern `java.time.Instant` (a moment in UTC).
.atZone( ZoneId.of( "Africa/Tunis" ) ) // Adjust from UTC to a particular time zone, to determine a date. Instantiating a `ZonedDateTime`.
.toLocalDate() // Extract a date-only `java.time.LocalDate` object from the date-time `ZonedDateTime` object.
)
Replacements:
Instant instead of java.util.DateBoth represent a moment in UTC. but now with nanoseconds instead of milliseconds.
LocalDate instead of java.sql.DateBoth represent a date-only value without a time of day and without a time zone.
Details
If you are trying to work with date-only values (no time-of-day, no time zone), use the LocalDate class rather than java.util.Date.
java.time
In Java 8 and later, the troublesome old date-time classes bundled with early versions of Java have been supplanted by the new java.time package. See Oracle Tutorial. Much of the functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
A SQL data type DATE is meant to be date-only, with no time-of-day and no time zone. Java never had precisely such a class† until java.time.LocalDate in Java 8. Let's create such a value by getting today's date according to a particular time zone (time zone is important in determining a date as a new day dawns earlier in Paris than in Montréal, for example).
LocalDate todayLocalDate = LocalDate.now( ZoneId.of( "America/Montreal" ) ); // Use proper "continent/region" time zone names; never use 3-4 letter codes like "EST" or "IST".
At this point, we may be done. If your JDBC driver complies with JDBC 4.2 spec, you should be able to pass a LocalDate via setObject on a PreparedStatement to store into a SQL DATE field.
myPreparedStatement.setObject( 1 , localDate );
Likewise, use ResultSet::getObject to fetch from a SQL DATE column to a Java LocalDate object. Specifying the class in the second argument makes your code type-safe.
LocalDate localDate = ResultSet.getObject( 1 , LocalDate.class );
In other words, this entire Question is irrelevant under JDBC 4.2 or later.
If your JDBC driver does not perform in this manner, you need to fall back to converting to the java.sql types.
Convert to java.sql.Date
To convert, use new methods added to the old date-time classes. We can call java.sql.Date.valueOf(…) to convert a LocalDate.
java.sql.Date sqlDate = java.sql.Date.valueOf( todayLocalDate );
And going the other direction.
LocalDate localDate = sqlDate.toLocalDate();
Converting from java.util.Date
While you should avoid using the old date-time classes, you may be forced to when working with existing code. If so, you can convert to/from java.time.
Go through the Instant class, which represents a moment on the timeline in UTC. An Instant is similar in idea to a java.util.Date. But note that Instant has a resolution up to nanoseconds while java.util.Date has only milliseconds resolution.
To convert, use new methods added to the old classes. For example, java.util.Date.from( Instant ) and java.util.Date::toInstant.
Instant instant = myUtilDate.toInstant();
To determine a date, we need the context of a time zone. For any given moment, the date varies around the globe by time zone. Apply a ZoneId to get a ZonedDateTime.
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant , zoneId );
LocalDate localDate = zdt.toLocalDate();
† The java.sql.Date class pretends to be date-only without a time-of-day but actually does a time-of-day, adjusted to a midnight time. Confusing? Yes, the old date-time classes are a mess.
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.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
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. Hibernate 5 & JPA 2.2 support java.time.
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 brought 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 (26+) bundle implementations of the java.time classes.
For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. 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.
With the other answer you may have troubles with the time info (compare the dates with unexpected results!)
I suggest:
java.util.Calendar cal = Calendar.getInstance();
java.util.Date utilDate = new java.util.Date(); // your util date
cal.setTime(utilDate);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
java.sql.Date sqlDate = new java.sql.Date(cal.getTime().getTime()); // your sql date
System.out.println("utilDate:" + utilDate);
System.out.println("sqlDate:" + sqlDate);
This function will return a converted SQL date from java date object.
public java.sql.Date convertJavaDateToSqlDate(java.util.Date date) {
return new java.sql.Date(date.getTime());
}
Converting java.util.Date to java.sql.Date will lose hours, minutes and seconds. So if it is possible, I suggest you to use java.sql.Timestamp like this:
prepareStatement.setTimestamp(1, new Timestamp(utilDate.getTime()));
For more info, you can check this question.
In my case of picking date from JXDatePicker (java calender) and getting it stored in database as SQL Date type, below works fine ..
java.sql.Date date = new java.sql.Date(pickedDate.getDate().getTime());
where pickedDate is object of JXDatePicker
This function will return a converted SQL date from java date object.
public static java.sql.Date convertFromJAVADateToSQLDate(
java.util.Date javaDate) {
java.sql.Date sqlDate = null;
if (javaDate != null) {
sqlDate = new Date(javaDate.getTime());
}
return sqlDate;
}
Format your java.util.Date first. Then use the formatted date to get the date in java.sql.Date
java.util.Date utilDate = "Your date"
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
final String stringDate= dateFormat.format(utilDate);
final java.sql.Date sqlDate= java.sql.Date.valueOf(stringDate);
Here the example of converting Util Date to Sql date and ya this is one example what i am using in my project might be helpful to you too.
java.util.Date utilStartDate = table_Login.getDob();(orwhat ever date your give form obj)
java.sql.Date sqlStartDate = new java.sql.Date(utilStartDate.getTime());(converting date)
I am a novice: after much running around this worked. Thought might be useful
String bufDt = bDOB.getText(); //data from form
DateFormat dF = new SimpleDateFormat("dd-MM-yyyy"); //data in form is in this format
Date bbdt = (Date)dF.parse(bufDt); // string data is converted into java util date
DateFormat dsF = new SimpleDateFormat("yyyy-MM-dd"); //converted date is reformatted for conversion to sql.date
String ndt = dsF.format(bbdt); // java util date is converted to compatible java sql date
java.sql.Date sqlDate= java.sql.Date.valueOf(ndt); // finally data from the form is convered to java sql. date for placing in database
Method for comparing 2 dates (util.date or sql.date)
public static boolean isSameDay(Date a, Date b) {
Calendar calA = new GregorianCalendar();
calA.setTime(a);
Calendar calB = new GregorianCalendar();
calB.setTime(b);
final int yearA = calA.get(Calendar.YEAR);
final int monthA = calA.get(Calendar.MONTH);
final int dayA = calA.get(Calendar.DAY_OF_YEAR);
final int yearB = calB.get(Calendar.YEAR);
final int monthB = calB.get(Calendar.MONTH);
final int dayB = calB.get(Calendar.DAY_OF_YEAR);
return yearA == yearB && monthA == monthB && dayA == dayB;
}
try with this
public static String toMysqlDateStr(Date date) {
String dateForMySql = "";
if (date == null) {
dateForMySql = null;
} else {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateForMySql = sdf.format(date);
}
return dateForMySql;
}
I think the best way to convert is:
static java.sql.Timestamp SQLDateTime(Long utilDate) {
return new java.sql.Timestamp(utilDate);
}
Date date = new Date();
java.sql.Timestamp dt = SQLDateTime(date.getTime());
If you want to insert the dt variable into an SQL table you can do:
insert into table (expireAt) values ('"+dt+"');
i am using the following code please try it out
DateFormat fm= new SimpleDateFormatter();
specify the format of the date you want
for example "DD-MM_YYYY" or 'YYYY-mm-dd' then use the java Date datatype as
fm.format("object of java.util.date");
then it will parse your date
You can use this method to convert util date to sql date,
DateUtilities.convertUtilDateToSql(java.util.Date)
I was trying the following coding that worked fine.
java.util.Date utilDate = new java.util.Date(); java.sql.Date
sqlDate = new java.sql.Date(utilDate);
If you are usgin Mysql a date column can be passed a String representation of this date
so i using the DateFormatter Class to format it and then set it as a String in the sql statement or prepared statement
here is the code illustration:
private String converUtilDateToSqlDate(java.util.Date utilDate) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String sqlDate = sdf.format(utilDate);
return sqlDate;
}
String date = converUtilDateToSqlDate(otherTransaction.getTransDate());
//then pass this date in you sql statement

String to Date Java

I am trying to convert the string "5/23/14 02:23:24" from a String in Eclipse to a Date to insert into a SQL statement. The code I have is as follows:
String dateAndTime = "5/23/14 02:23:24";
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy HH:mm:ss");
Date date = sdf.parse(dateAndTime);
long dateLong = date.getTime();
insertStatement.setDate(1, new java.sql.Date(dateLong));
I expect to see
23-MAY-2014 2.23.24.000000000 PM
in my table, but instead I see
23-MAY-2014 12.00.00.000000000 AM
Can anyone shed some light on what I am doing wrong?
Thanks!
A standard DATE SQL type doesn't have any time information associated with it, so the javadocs for java.sql.Date state:
To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated.
You'll want to use a java.sql.Timestamp instead. It corresponds to the SQL type TIMESTAMP, which holds date and time of day data.
You're calling setDate, which uses a java.sql.Date. That represents just a date, not a date and time.
You should consider using setTimestamp instead, with a java.sql.Timestamp. (There may be other ways of doing it for your specific database, but that's probably the simplest general solution):
long dateLong = date.getTime();
insertStatement.setTimestamp(1, new java.sql.Timestamp(dateLong));
java.time
The legacy date-time API (java.util date-time types and their formatting API, SimpleDateFormat) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time, the modern date-time API*.
Solution using modern date-time API:
Parse the date-time string into LocalDateTime:
String dateAndTime = "5/23/14 02:23:24";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/uu H:m:s", Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.parse(dateAndTime, dtf);
Set the instance of LocalDateTime into the database using PreparedStatement#setObject:
Statement st = conn.createStatement();
PreparedStatement st = conn.prepareStatement("INSERT INTO mytable (columnfoo) VALUES (?)");
st.setObject(1, ldt);
st.executeUpdate();
st.close();
In order to read it from the database, use Resultset#getObject:
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM mytable WHERE ...");
while (rs.next()) {
LocalDateTime ldt = rs.getObject(1, LocalDateTime.class));
System.out.println(ldt);
}
rs.close();
st.close();
Learn more about the the modern date-time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

How to convert a date a user selects in MM-dd-yyyy format to the format yyyy-MM-dd in Java

I want to convert the incoming date from MM-dd-yyyy which is the format on the front end, and convert it to the format yyyy-MM-dd. This is useful since the backend query requires the format to be yyyy-MM-dd. I am having trouble with the syntax. I know when I do Date = new Date(), that only initializes for today's date but I want the paramater to be the incoming date that the user selects, which can be whatever it wants to be. I have two date formats set up:
public final static String getConvertedDate()
{
DateFormat userFormat = new SimpleDateFormat(MM-dd-yyyy);
DateFormat neededFormat = new SimpleDateFormat(yyyy-MM-dd);
//now I want to set it up to where I have a date the user selects
Date date = new Date() //I feel like I should input a parameter for any given date in Date() but am //unsure
//return statement returning the neededFormat
}
I may or may not be setting it up properly and am unsure if I need to set up two DateFormats like that. Any help would be much appreciated. Thanks!
You said, you want to convert a date with a given format, but you don't have a parameter for that.
public final static String getConvertedDate(String givenDaten) throws ParseException
{
DateFormat userFormat = new SimpleDateFormat(MM-dd-yyyy);
DateFormat neededFormat = new SimpleDateFormat(yyyy-MM-dd);
//first parse the userformatted date
Date userFormatDate = userFormat.parse(givenDate);
//format it as needed
return neededFormat.format(date);
}
This should do the trick:
public String convertDate(String input) throws ParseException{
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
Date temp = sdf.parse(input);
sdf.applyPattern("yyyy-MM-dd");
return sdf.format(temp);
}
You should look at the format function for SimpleDateFormat
A quick example would be
public final static String getConvertedDate(String userDate)
{
DateFormat userFormat = new SimpleDateFormat(MM-dd-yyyy);
DateFormat neededFormat = new SimpleDateFormat(yyyy-MM-dd);
// Turn the String of the userDate into a date with the first format
Date formatUserDate = userFormat.parse(userDate);
// Now format that date into the correct format you want to return
return neededFormat.format(formatUserDate);
}
You need to actually parse the input String using your DateFormat:
public static void main(String[] args) throws Exception {
final DateFormat in = new SimpleDateFormat("MM-dd-yyyy");
final Date date = in.parse("03-11-2013");
System.out.println(date);
final DateFormat out = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(out.format(date));
}
Output:
Mon Mar 11 00:00:00 CET 2013
2013-03-11
Note, you're probably better off using the Date object in your code. JDBC can accept the Date with only a simple conversion to a java.sql.Date and you can convert it to any format your need later.
I would also promote the formats for class members as they are expensive to construct so should be reused, although it should be noted that they are not thread safe.
tl;dr
LocalDate.parse(
"01-23-2017" ,
DateTimeFormatter.ofPattern( "MM-dd-uuuu" )
).toString()
2017-01-23
Using java.time
You are using troublesome old date-time classes now supplanted by java.time classes.
String input = "01-23-2017" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM-dd-uuuu" ) ;
LocalDate ld = LocalDate.parse( input , f );
Your desired output happens to be standard ISO 8601. The java.time classes use the standard formats by default when parsing/generating strings.
String output = ld.toString() ;
2017-01-23
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
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.

Get only the date from the timestamp

This is my Below function in which I am passing timestamp, I need only the date in return from the timestamp not the Hours and Second. With the below code I am getting-
private String toDate(long timestamp) {
Date date = new Date (timestamp * 1000);
return DateFormat.getInstance().format(date).toString();
}
This is the output I am getting.
11/4/01 11:27 PM
But I need only the date like this
2001-11-04
Any suggestions?
Use SimpleDateFormat instead:
private String toDate(long timestamp) {
Date date = new Date(timestamp * 1000);
return new SimpleDateFormat("yyyy-MM-dd").format(date);
}
Updated: Java 8 solution:
private String toDate(long timestamp) {
LocalDate date = Instant.ofEpochMilli(timestamp * 1000).atZone(ZoneId.systemDefault()).toLocalDate();
return date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
}
You can use this code to get the required results
protected Timestamp timestamp = new Timestamp(Calendar.getInstance().getTimeInMillis());
protected String today_Date=timestamp.toString().split(" ")[0];
java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Also, quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time, the modern Date-Time API:
You can use Instant#ofEpochSecond to get an Instant out of the given timestamp and then use LocalDate.ofInstant to get a LocalDate out of the obtained Instant.
Demo:
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
public class Main {
public static void main(String[] args) {
// Test
System.out.println(toDate(1636120105L));
}
static LocalDate toDate(long timestamp) {
return LocalDate.ofInstant(Instant.ofEpochSecond(timestamp), ZoneId.systemDefault());
}
}
Output:
2021-11-05
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time. Check this answer and this answer to learn how to use java.time API with JDBC.
* If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring. Note that Android 8.0 Oreo already provides support for java.time.
Joda-Time
The Joda-Time library offers a LocalDate class to represent a date-only value without any time-of-day nor time zone.
Time Zone
Determining a date requires a time zone. A moment just after midnight in Paris means a date that is a day ahead of the same simultaneous moment in Montréal. If you neglect to specify a time zone, the JVM’s current default time zone is applied – probably not what you want as results may vary.
Example Code
long millisecondsSinceUnixEpoch = ( yourNumberOfSecondsSinceUnixEpoch * 1000 ); // Convert seconds to milliseconds.
DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" );
LocalDate localDate = new LocalDate( millisecondsSinceUnixEpoch, timeZone );
String output = localDate.toString(); // Defaults to ISO 8601 standard format, YYYY-MM-DD.
Previous Day
To get the day before, as requested in a comment.
LocalDate dayBefore = localDate.minusDays( 1 );
Convert to j.u.Date
The java.util.Date & .Calendar classes should be avoided as they are notoriously troublesome. But if required, you may convert.
java.util.Date date = localDate.toDate(); // Time-of-day set to earliest valid for that date.

Categories