Search code examples
javadatejava.util.date

java util date value of string


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);}

Solution

  • 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.