3 Replies Latest reply: Oct 6, 2009 12:48 PM by 807580 RSS

    Casting String to Date value


      I currently have two string params that I catch with success, have for several years now, that entail retrieving a string val thru request.getParameter, then converting that string to a Date thru this cast:
                String datereq = request.getParameter("date_req").trim();
                Date dtreq = Date.valueOf(datereq);
                String vpdate = request.getParameter("vp_date");
                Date dt = Date.valueOf(vpdate);
      Both work just fine! One is a hidden, hard-coded value, and the other is an object from a date picker calendar.

      However, if I add the following:
      if (request.getParameter("critexpdate")==null || request.getParameter("critexpdate")== "" ) {
           critexpldatereq = "1900-01-01";
      else {critexpldatereq = request.getParameter("critexpdate");
      System.out.println("critexpldatereq- "+critexpldatereq);
                Date critdtreq = Date.valueOf(critexpldatereq);
      System.out.println("critdtreq- "+critdtreq);
      I get no value at all passed. The error tells me:
           at java.sql.Date.valueOf(Date.java:100)

      I'm mystified how this would work for my other two variables and values, and would not work here.
      My other vpdate value is passed in the same manner and format as the placeholder date, 1900-01-01 ,above.

      I welcome any feedback on this - I know it's a bit antiquated, but I'm using JDK 1.4.2.

        • 1. Re: Casting String to Date value
          You should very likely be using SimpleDateFormat.parse all over the place here
          • 2. Re: Casting String to Date value
            Indeed. To convert String to Date, use [SimpleDateFormat#parse()|http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html]. Please note that you end up with java.util.Date, not with java.sql.Date. You shouldn't use java.sql.Date anywhere outside the database logic.

            That said, there is no means of casting here. Casting is roughly said just a "conversion" between a class and its sub- or superclass. String and Date are in no way sub/superclass of each other. The following cast example ain't going to work at all: Date date = (Date) string; Please polish your basic Java skills and terminology.
            • 3. Re: Casting String to Date value
              Ok, thanks for the tips.