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 conver
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+"');
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);
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
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)
java.sql.Date sqlDate = new java.sql.Date(javaDate.getTime());
Here javaDate is the instance of java.util.Date
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;
}