How to cast java.util.date to java.sql.date? [duplicate] - java

This question already has answers here:
How to convert java.util.Date to java.sql.Date?
(17 answers)
Closed 8 years ago.
Date date = new Date();
DateFormat dt = new SimpleDateFormat("yyyy-MM-dd");
try {
date = dt.parse("2014-03-14");
} catch (ParseException parseException) {
}
orderBean.setDate((java.sql.Date) date);
when I try to cast util.date to sql.date using above code an error occurs as below. I am using mysql data base to store a data.
can anyone help me?
Mar 14, 2014 11:16:44 AM gui.salespot jButton1ActionPerformed
SEVERE: null
java.lang.ClassCastException: java.util.Date cannot be cast to java.sql.Date

No. You cannot cast different type of Objects like that.
instead you can get the time which is long and use it.
java.sql.Date sDate = new java.sql.Date(date.getTime());

try this way
Date date = new Date();
java.sql.Date d=new java.sql.Date(date.getTime());

java.sql.Date extends from java.util.Date, so you can case java.sql.Date to java.util.Date but not the other way round.
Try using...
orderBean.setDate(new java.sql.Date(date.getTime()));
Instead...

java.util.Date is superclass of java.sql.Date you can not type cast it by this way.
try with - java.sql.Date#Date(long)
Snippet -
java.sql.Date sqlDate = new java.sql.Date(date.getTime())

look like simple....
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 click

Use this answer to convert date.
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);
For your concern copy my code.
Date date = new Date();
DateFormat dt = new SimpleDateFormat("yyyy-MM-dd");
try {
date = dt.parse("2014-03-14");
} catch (ParseException parseException) {
}
orderBean.setDate(new java.sql.Date(date.getTime()));
Check this reference.. Thanks..

Related

How do I parse a date string into a Joda DateTime object for java? [duplicate]

This question already has answers here:
Converting a date string to a DateTime object using Joda Time library
(10 answers)
Closed 7 years ago.
The code below is the best I have come up with so far. The .setTime() methods are throwing a exception. Is there a better way to do this or correct this?
String format = "MM/dd/yyyy";
DateTime test = new DateTime();
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy");
SimpleDateFormat formater = new SimpleDateFormat(format);
String startDateString = "09/10/2015";
String endDateString = "09/20/2015";
Date startDate = null;
Date endDate = null;
Calendar sampleDateStart = null;
Calendar sampleDateEnd = null;
try{
startDate = formater.parse(startDateString);
endDate = formater.parse(endDateString);
sampleDateStart.setTime(startDate);
sampleDateEnd.setTime(endDate);
}catch(Exception e){
System.out.println(e.getMessage());
}
You already created the DateTimeFormatter that your need, so just use it:
DateTimeFormatter formater = DateTimeFormat.forPattern("MM/dd/yyyy");
DateTime startDateTime = formater.parseDateTime("09/10/2015");
DateTime endDateTime = formater.parseDateTime("09/20/2015");
No need for a SimpleDateFormat or a Calendar.
Note: I fixed the creation of the DateTimeFormatter to Joda, since you were doing it the Java 8 way.
Seems fine if you fix the initialization of the Calendar variables:
Calendar sampleDateStart = Calendar.getInstance();
Calendar sampleDateEnd = Calendar.getInstance();
The problem would have been more obvious if you had used the correct exception type as recommended,
instead of the generic Exception,
and printing the stack trace instead of e.getMessage():
try {
startDate = formater.parse(startDateString);
endDate = formater.parse(endDateString);
sampleDateStart.setTime(startDate);
sampleDateEnd.setTime(endDate);
} catch (ParseException e) {
e.printStackTrace();
}
The stack trace would have told you the exact line where NullPointerException was thrown.

java.util.Date cannot be cast to java.sql.Date [duplicate]

This question already has answers here:
java.util.Date vs java.sql.Date
(7 answers)
Closed 5 years ago.
I am trying to insert Date into Database but I am getting error as java.util.Date cannot be cast to java.sql.Date.
Please help.
String next_dt = req.getParameter("NextDate");
DateFormat dtFmt = null;
dtFmt = new SimpleDateFormat("yyyy-MM-dd");
dtToday = (Date) dtFmt.parse(next_dt);
You have imported java.sql.Data. But dtFmt.parse(next_dt); returns an object of type java.util.Date so you have to change
import java.sql.Date;
to
import java.util.Date;
DateFormat.parse() returns a java.util.Date, and you're trying to illegally cast it to a java.sql.Date.
Assuming you continue to import java.sql.Date, you can successfully assign the variable like so:
dtToday = new Date(dtFmt.parse(next_dt).getTime());
You should use java.sql.Timestamp or java.sql.Date instead of java.util.Date
Problem with java.sql.Date is that it will not store time. So using Timestamp is the approach i always take. As it is the child class of java.util.date it is compatible with both date and timestamp columns in DB.
Add following lines - as it needs to be a sql Date and not util date
java.sql.Date sqlDate = new java.sql.Date(dtToday.getTime());
//now insert this sqlDate
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;
}
As the name of the class is same use should give fully qualified name(FQN) of both classes you also can use format method to convert date to proper SQL format date.
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;
}

Incorrect date returned when converting from java.util.date to java.sql.date

I am using Eclipse Juno, GWT and java.
When I convert
I get the date via:
dateBoxDOB = new DateBox();
dateBoxDOB.setFormat(new DefaultFormat(DateTimeFormat.getFormat("dd-MM-yyyy")));
flexTable.setWidget(0, 1, dateBoxDOB);
dateBoxDOB.getDatePicker();
Where I enter 20/04/1961. I then need to convert it from java.util.date to java.sql.date before saving it to MySQL:
java.sql.Date sqlDOB = new java.sql.Date(dateBoxDOB.getValue().getTime());
Window.alert("Util date = " + dateBoxDOB.getValue().getTime());
Window.alert("DOB = " + sqlDOB);
java.sql.Date sqlDateArchived = new java.sql.Date(dateBoxArchived.getValue().getTime());
java.sql.Date sqlPackIn = new java.sql.Date(dateBoxPackIn.getValue().getTime());
java.sql.Date sqlPackOut = new java.sql.Date(dateBoxPackOut.getValue().getTime());
The date displayed by the window alert is -233920800000 for util and 1962-08-04 for sql.
How do I get the correct date please (i.e., 1961-04-20 from sql date)?
Also, if a date is null and exception is thrown. How do I get around this please?
This code works fine for me.
You are getting this issue because you defined the format as dd-MM-yyyy and entered date as 20/04/1961. Notice the change in format '-' vs '/'.
This may help you
Calendar cal = Calendar.getInstance();
DateFormat df=new SimpleDateFormat("dd/mm/yyyy");
String dateStr="20/04/1961";
Date date = df.parse(dateStr);
cal.setTime(date);
Date sqlDate = new java.sql.Date(cal.getTime().getTime());
System.out.println("utilDate:" + df.format(date));
System.out.println("sqlDate:" + df.format(sqlDate));

java.sql.Date and java.sql.Time to org.joda.time.DateTime

As the question title says,
I have java.sql.Date and java.sql.Time as input
Now I want to convert them to a DateTime object, but since the getDay, getYear etc. methods are deprecated I can't figure out how to combine the two...
Just see if this does the trick for you.
Date date = new Date(System.currentTimeMillis()); // Prints 2013-03-08
Time time = new Time(System.currentTimeMillis()); // Prints 15:40:33
String myDate = date + " " + time;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date utilDate = new java.util.Date();
try {
utilDate = sdf.parse(myDate); // You get a Java Util Date object(Fri Mar 08 15:40:33 IST 2013)
} catch (ParseException pe) {
// TODO something.
}
DateTime dateTime = new DateTime(utilDate); // You get your JODA object.
You could create a DateTime object from the date and add a Duration object to that DateTime object, resulting in a single object whcih is the Date + Time instant in time represented by your input.
Something like the following:
Date d = //your Date
Time t = //your time
DateTime result = new DateTime(d).plus(t.getTime());
This will result in an Immutable object representing the instant you want....I I understood your question correctly and what you are after is a way of "adding" two different classes representing time.
Just do some tricks on java.sql.Time: calculate the duration. java.sql.Time set date components to January 1, 1970 implicitly.
java.sql.Date epoch = new Date(70, 0, 1);
java.sql.Date date = new Date(113, 2, 8);
java.sql.Time time = new Time(1, 1, 1);
DateTime dt = new DateTime(date.getTime())
.plus(time.getTime() - epoch.getTime());
System.out.println(date);
System.out.println(time);
System.out.println(dt);

Get yesterday's date using Date [duplicate]

This question already has answers here:
How to check if a date Object equals yesterday?
(9 answers)
Closed 8 years ago.
The following function produces today's date; how can I make it produce only yesterday's date?
private String toDate() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
return dateFormat.format(date).toString();
}
This is the output:
2012-07-10
I only need yesterday's date like below. Is it possible to do this in my function?
2012-07-09
Update
There has been recent improvements in datetime API with JSR-310.
Instant now = Instant.now();
Instant yesterday = now.minus(1, ChronoUnit.DAYS);
System.out.println(now);
System.out.println(yesterday);
https://ideone.com/91M1eU
Outdated answer
You are subtracting the wrong number:
Use Calendar instead:
private Date yesterday() {
final Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
return cal.getTime();
}
Then, modify your method to the following:
private String getYesterdayDateString() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
return dateFormat.format(yesterday());
}
See
IDEOne Demo
You can do following:
private Date getMeYesterday(){
return new Date(System.currentTimeMillis()-24*60*60*1000);
}
Note: if you want further backward date multiply number of day with 24*60*60*1000 for example:
private Date getPreviousWeekDate(){
return new Date(System.currentTimeMillis()-7*24*60*60*1000);
}
Similarly, you can get future date by adding the value to System.currentTimeMillis(), for example:
private Date getMeTomorrow(){
return new Date(System.currentTimeMillis()+24*60*60*1000);
}
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Today's date is "+dateFormat.format(cal.getTime()));
cal.add(Calendar.DATE, -1);
System.out.println("Yesterday's date was "+dateFormat.format(cal.getTime()));
Use Calender Api
Try this one:
private String toDate() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
// Create a calendar object with today date. Calendar is in java.util pakage.
Calendar calendar = Calendar.getInstance();
// Move calendar to yesterday
calendar.add(Calendar.DATE, -1);
// Get current date of calendar which point to the yesterday now
Date yesterday = calendar.getTime();
return dateFormat.format(yesterday).toString();
}
Try this;
public String toDate() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
return dateFormat.format(cal.getTime());
}
changed from your code :
private String toDate(long timestamp) {
Date date = new Date (timestamp * 1000 - 24 * 60 * 60 * 1000);
return new SimpleDateFormat("yyyy-MM-dd").format(date).toString();
}
but you do better using calendar.
There is no direct function to get yesterday's date.
To get yesterday's date, you need to use Calendar by subtracting -1.
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Today's date is "+dateFormat.format(cal.getTime()));
cal.add(Calendar.DATE, -1);
System.out.println("Yesterday's date was "+dateFormat.format(cal.getTime()));

Categories