This is a method in an EJB for adding booking, I'm trying to set a to value of String Arr because Arr is a string which gets the form value in the Servlet and I want to do the same for d to value of String Dept. I'm using java.util.Date, it works for java.sql.Date but not for java.util.Date.
public void addBooking(String Arr, String Dept, String username, String roomnum){
BookingTableClass booking = new BookingTableClass();
Date a= Date.valueOf(Arr);//the problem is in these four lines
booking.setarrivalDate(a);
Date d= Date.valueOf(Dept);
booking.setdeptDate(d);
booking.setCustomerUsername(username);
Long rmnum = Long.valueOf(roomnum);
booking.setRoomNumber(rmnum);}
Maybe you're not using a correct format for the Date type and you have to specify the format that you're using, for this purpose use SimpleDateFormat class.
SimpleDateFormat textFormat = new SimpleDateFormat("yyyy-MM-dd");
String paramDateAsString = "2007-12-25";
Date myDate = null;
myDate = textFormat.parse(paramDateAsString);
Hope it helps. Best regards.
You can convert a java.util.Date into a java.sql.Date object like this:
java.util.Date now = new java.util.Date();
java.sql.Date date = new java.sql.Date(now.getTime());
That is, you obtain the java.util.Date equivalent in milliseconds and then use this value to initialize the java.sql.Date object.
Related
I am calling a Web Service which accepts date as Xmlgregoriancalendar of format "07/23/2015T00:00:00Z" but what I have currently from my database is "2015-23-07T00:00:00Z".
How to convert this String type of XMLGregorianCalender of type
"MM/dd/yyyy'T'HH:mm:ss.SSS'Z'"
Since that service is hosted by some third party I can't change the schema and need to implement this conversion.
I tried this
Date d = new Date();
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy/MM/dd'T'HH:mm:ss.SSS'Z'");
String formattedDate1 = sdf1.format(d);
Date date = sdf1.parse(formattedDate1);
GregorianCalendar gregorianCalendar;
XMLGregorianCalendar result = null;
gregorianCalendar = (GregorianCalendar)GregorianCalendar.getInstance();
gregorianCalendar.setTime(date);
result = DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCalendar);
java.text.DateFormat outputFormat =new java.text.SimpleDateFormat("MM/dd/yyyy'T'HH:mm:ss'Z'");
java.text.DateFormat outputFormat1 =new java.text.SimpleDateFormat("yyyy-dd-MM'T'HH:mm:ss'Z'");
System.out.println(outputFormat.format(outputFormat1.parse("2015-23-07T00:00:00Z")));//07/23/2015T00:00:00Z
You can using SimpleDateFormat to do this.
Grab the string from database, find and replace "-" with "\" then parse String to Date. Actually, SimpleDateFormat would accept "MM-dd-yyyy'T'HH:mm:ss.SSS'Z'" type as well as "MM/dd/yyyy'T'HH:mm:ss.SSS'Z'" and you can do some calculation on it.
I tried to see questions about date convert issues between two database using java but didn't solve my problem.
Here is the current date to insert in my database with a DateTime format :
java.sql.Date SQLDateValue = new java.sql.Date(System.currentTimeMillis()) ;
preparedStatement.setDate(index, SQLDateValue);
And here is the Timestamp from an API named Vdoc, convert to String and i tried to convert it to java.sql.Date (DateTime) :
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date DateValue = (java.util.Date) this.getWorkflowInstance().getValue(this.ListeChamps[i][2]);
String StringDateValue = DateValue.toString();
java.sql.Date SQLDateValue = new java.sql.Date (sdf.parse(StringDateValue).getTime());
preparedStatement.setDate(index, SQLDateValue);
The second line return a field value containing a String but i need to use toString().
The following error message is :
Failed to convert the date and / or time from a string.
Both of my date parameters are java.sql.date, i don't understand.
If you have an idea of what happens with this, it would be nice to help me.
Ezerah
Sorry for my bad english
Just construct the java.sql.Date from java.util.Date.
Call java.util.Date::getTime to extract the count of milliseconds from epoch. Pass that count to constructor of java.sql.Date.
In your case below should work.
java.util.Date DateValue = (java.util.Date) this.getWorkflowInstance().getValue(this.ListeChamps[i][2]);
java.sql.Date SQLDateValue = new java.sql.Date (DataValue.getTime());
preparedStatement.setDate(index, SQLDateValue);
try this:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date DateValue = **sdf.parse(**this.getWorkflowInstance().getValue(this.ListeChamps[i][2])**)**;
String StringDateValue = DateValue.toString();
java.sql.Date SQLDateValue = new java.sql.Date (sdf.parse(StringDateValue).getTime());
preparedStatement.setDate(index, SQLDateValue);
You can't cast String to Date, you should parse it
I have a simple problem while converting String to SQL date.
java.sql.Date sqlDate = getSqlDateFormat("2010-10-10");
Expected to store 2010-10-10 in the H2 database but it stores 2009-12-27 instead.
Any help will be appreciated.
public static java.sql.Date getSqlDateFormat(String dateInString) {
java.util.Date date = transformFromStringToDate(dateInString);
return convertUtilDateToSqlDate(date);
}
The method in turn calls transformFromStringToDate() to convert the input String into java.util.Date
public static java.util.Date transformFromStringToDate(String dateInString) {
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd", Locale.ENGLISH);
java.util.Date utilDate = dateFormat.parse(dateInString);
return utilDate;
}
Finally I'm calling the convertUtilDateToSqlDate() to store it in the database
public static Date convertUtilDateToSqlDate(java.util.Date date)
{
Date sqlDate = new Date(date.getTime());
return sqlDate;
}
change your format to yyyy-MM-dd The year must be lowercase y rather than uppercase.
If you see the documentation of SimpleDateFormat Yis the Week year.
y is the field Year
Is it possible to do format a date of type String using a date formatter? I want to store my Date and Time in the Event class as Strings so that I don't need to convert the Strings loaded from a MYSQL database (using the types DATE and TIME) back into Date types so they can be stored in new Event objects. MySQL only accepts DATE in the format of YYYY-MM-DD and TIME in the format of HH:MM:SS but i want these to be formatted differently when i go to print them out in my program.
When i run this code i get an Cannot format given Object as a Date at java.text.DateFormat.format(Unknown Source) error. If i try using parse() it won't compile because it only accepts Dates.
Main class
public Main() {
ArrayList<Event> events = new ArrayList<Event>();
private SimpleDateFormat timeFormat = new SimpleDateFormat("HH:MM:SS");
private SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-DD");
//Stores current time and date
Date date;
Date time;
String d = "";
String t = "";
d= dateFormat.parse(date);
t= timeFormat.parse(time);
events.add(d, t);
//Print out newly formatted date and time when loaded from mysql
System.out.println(events.get(0).printDate());
System.out.println(events.get(0).printTime());
}
Events class
public class Event {
private String date;
private String time;
public Event(String d, String t) {
date = d;
time = t;
}
public String printDate() {
SimpleDateFormat format = new SimpleDateFormat("DD/MM/YYYY");
String newDate = format.format(date);
return newDate;
}
public String printTime() {
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
String newTime = format.format(time);
return newTime;
}
}
In Event, you should use Date type for date and time field.
This is a more appropriate representation for date and time value. And with them, you can use DateFormat to do whatever formatting you want
(It will be even better to use Joda time LocalDate and LocalTime for your date and time, but that's a bit off topic)
You can't format your dates because they are String objects and SimpleDateFormat needs Date objects.
You should consider a different way of storing them (either as Date or Calendar). See below:
public class Event
{
private Date date;
private Date time;
public Event(String d, String t)
{
String[] details = d.split("\\-");
Calendar c = Calendar.getInstance();
c.set(Integer.parseInt(details[0]), Integer.parseInt(details[1]), Integer.parseInt(details[2]));
date = c.getTime();
details = t.split(":");
c.set(Integer.parseInt(details[0]), Integer.parseInt(details[1]), Integer.parseInt(details[2]));
time = c.getTime();
}
public String printDate()
{
SimpleDateFormat format = new SimpleDateFormat("dd/MM/YYYY");
String newDate = format.format(date);
return newDate;
}
// rest of you class can stay the way it is
}
You can format java.util.Date or java.sql.Date (which is subclass of java.util.Date) using date formatter, eg:
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
String dateStr = df.format(date);
Using jdbc ResultSet getDate() method you can obtain java.sql.Date object which you can print in any format using method above
Similar techniques can also be used to parse string in any format into a java.util.Date object
Date date = df.parse(dateStr);
Check the javadoc for the right formatting codes. Try this:
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
I having method that i move type object (in this time type object is type String)
and i want to cast it to type date how should i do that .
when i use the following code i getting error :
java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Date
Code:
} else if (typeName.equals("Date")) {
return new SwitchInputType<Date>((Date) memberValue);
Something like this should work:
final SimpleDateFormat parsedDate = new SimpleDateFormat("yyyy-MM-dd");
final Date date;
try{
date = parsedDate.parse(stringValue);
} catch(Exception e) {
// handle the exception.
}
How to parse a date?
SimpleDateFormat parserSDF=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = parserSDF.parse(memberValue);
If its a string, you need to parse it. Try using SimpleDateFormat with appropriate format.
Try to create new date object like this Date date = new Date(long) or if you created this string using Date class use its static method Date.valueOf(String s).
You should first convert the string to date object before assigning to a Date. Use SimpleDateFormat.parse() method to parse the string to a Date object.
You can use:
return new SwitchInputType<Date>(new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(memberValue));
You cannot simply cast a String to a Date. To get a Date from a String object which has the String representation of Date, use SimpleDateFormat.
E.g:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); //Change format according to your needs.
Date date = new Date();
try{
date = sdf.parse((String)memberValue); //Update:- memberValue.toString() will also work.
}catch(ParseException pe){
//Do something on Exception.
}
return new SwitchInputType<Date>(date);