Sql time to util date

hi mates
can any one give me the java code to convert sql time to util date?
thanks in advance

Since java.sql.Time extends java.util.Date it is a
Date. Am i right here?How about looking it up? Then you'd know.
Yes, sql.Date extends util.Date.Sorry. I'm getting screen-tired. sql.Time extends util.Date, too. But they only show the time, no date.

Similar Messages

  • Convert util.Date to sql.Date with time being displayed!

    Hi all,
    I want to convert util.Date to sql.Date for passing the same to Database. (i donot want to use Timstamp, for some reasons)
    java.sql.Date sqldate =
    new java.sql.Date(new java.util.Date().getTime());
    This simple code truncates the Time component and the result will be only Date. But my requirement is for Data and Time, both.
    Request anyone to suggest how to go abt this problem.
    Thanx.

    You can use the class java.text.DateFormat (java.text.SimpleDateFormat) for displaying. For example like this.
    java.sql.Date sqldate = new java.sql.Date(new java.util.Date().getTime());
    java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("yyyy.MM.dd 'at' HH:mm:ss z");
    String str = formatter.format(sqldate);
    System.out.println(str);

  • Java.sql.Date vs java.util.Date vs. java.util.Calendar

    All I want to do is create a java.sql.Date subclass which has the Date(String) constructor, some checks for values and a few other additional methods and that avoids deprecation warnings/errors.
    I am trying to write a wrapper for the java.sql.Date class that would allow a user to create a Date object using the methods:
    Date date1 = new Date(2003, 10, 7);ORDate date2 = new Date("2003-10-07");I am creating classes that mimic MySQL (and eventually other databases) column types in order to allow for data checking since MySQL does not force checks or throw errors as, say, Oracle can be set up to do. All the types EXCEPT the Date, Datetime, Timestamp and Time types for MySQL map nicely to and from java.sql.* objects through wrappers of one sort or another.
    Unfortunately, java.sql.Date, java.sql.Timestamp, java.sql.Time are not so friendly and very confusing.
    One of my problems is that new java.sql.Date(int,int,int); and new java.util.Date(int,int,int); are both deprecated, so if I use them, I get deprecation warnings (errors) on compile.
    Example:
    public class Date extends java.sql.Date implements RangedColumn {
      public static final String RANGE = "FROM '1000-01-01' to '8099-12-31'";
      public static final String TYPE = "DATE";
       * Minimum date allowed by <strong>MySQL</strong>. NOTE: This is a MySQL
       * limitation. Java allows dates from '0000-01-01' while MySQL only supports
       * dates from '1000-01-01'.
      public static final Date MIN_DATE = new Date(1000 + 1900,1,1);
       * Maximum date allowed by <strong>Java</strong>. NOTE: This is a Java limitation, not a MySQL
       * limitation. MySQL allows dates up to '9999-12-31' while Java only supports
       * dates to '8099-12-31'.
      public static final Date MAX_DATE = new Date(8099 + 1900,12,31);
      protected int _precision = 0;
      private java.sql.Date _date = null;
      public Date(int year, int month, int date) {
        // Deprecated, so I get deprecation warnings from the next line:
        super(year,month,date);
        if(! isWithinRange(this))
          throw new ValueOutOfRangeException((RangedColumn)this, "" + this);
      public Date(String s) {
        super(0l);
        // Start Cut-and-paste from java.sql.Date.valueOf(String s)
        int year;
        int month;
        int day;
        int firstDash;
        int secondDash;
        if (s == null) throw new java.lang.IllegalArgumentException();
        firstDash = s.indexOf('-');
        secondDash = s.indexOf('-', firstDash+1);
        if ((firstDash > 0) & (secondDash > 0) & (secondDash < s.length()-1)) {
          year = Integer.parseInt(s.substring(0, firstDash)) - 1900;
          month = Integer.parseInt(s.substring(firstDash+1, secondDash)) - 1;
          day = Integer.parseInt(s.substring(secondDash+1));
        } else {
          throw new java.lang.IllegalArgumentException();
        // End Cut-and-paste from java.sql.Date.valueOf(String s)
        // Next three lines are deprecated, causing warnings.
        this.setYear(year);
        this.setMonth(month);
        this.setDate(day);
        if(! isWithinRange(this))
          throw new ValueOutOfRangeException((RangedColumn)this, "" + this);
      public static boolean isWithinRange(Date date) {
        if(date.before(MIN_DATE))
          return false;
        if(date.after(MAX_DATE))
          return false;
        return true;
      public String getRange() { return RANGE; }
      public int getPrecision() { return _precision; }
      public String getType() { return TYPE; }
    }This works well, but it's deprecated. I don't see how I can use a java.util.Calendar object in stead without either essentially re-writing java.sql.Date almost entirely or losing the ability to be able to use java.sql.PreparedStatement.get[set]Date(int pos, java.sql.Date date);
    So at this point, I am at a loss.
    The deprecation documentation for constructor new Date(int,int,int)says "instead use the constructor Date(long date)", which I can't do unless I do a bunch of expensive String -> [Calendar/Date] -> Milliseconds conversions, and then I can't use "super()", so I'm back to re-writing the class again.
    I can't use setters like java.sql.Date.setYear(int) or java.util.setMonth(int) because they are deprecated too: "replaced by Calendar.set(Calendar.DAY_OF_MONTH, int date)". Well GREAT, I can't go from a Date object to a Calendar object, so how am I supposed to use the "Calendar.set(...)" method!?!? From where I'm sitting, this whole Date deprecation thing seems like a step backward not forward, especially in the java.sql.* realm.
    To prove my point, the non-deprecated method java.sql.Date.valueOf(String) USES the DEPRECATED constructor java.util.Date(int,int,int).
    So, how do I create a java.sql.Date subclass which has the Date(String) constructor that avoids deprecation warnings/errors?
    That's all I really want.
    HELP!

    I appreciate your help, but what I was hoping to accomplish was to have two constructors for my java.sql.Date subclass, one that took (int,int,int) and one that took ("yyyy-MM-dd"). From what I gather from your answers, you don't think it's possible. I would have to have a static instantiator method like:public static java.sql.Date createDate (int year, int month, int date) { ... } OR public static java.sql.Date createDate (String dateString) { ... }Is that correct?
    If it is, I have to go back to the drawing board since it breaks my constructor paradigm for all of my 20 or so other MySQL column objects and, well, that's not acceptable, so I might just keep my deprecations for now.
    -G

  • Java.sql.Date and java.util.Date - class loaded first in the classpath

    I had two jar files which has java.util.Date and java.sql.Date class file. i want to know whether which class is loaded first in the classpath...
    I like to change the order of loading the class at runtime...
    Is there is any way to change the order of loading of class...
    I may have different version of jar files for example xerces,xercesImpl. some of the code uses xerces ,some of the code uses xercesImpl..i had common classes.
    I like to load the class with the same name according to the order i need..
    Can we do all these in Run time ?????

    I had two jar files which has java.util.Date and
    java.sql.Date class file. i want to know whether
    which class is loaded first in the classpath...
    I like to change the order of loading the class at
    runtime...
    Is there is any way to change the order of loading of
    class...
    I may have different version of jar files for example
    xerces,xercesImpl. some of the code uses xerces ,some
    of the code uses xercesImpl..i had common classes.
    I like to load the class with the same name according
    to the order i need..
    Can we do all these in Run time ?????That is meaningless.
    The classes you are referring to are part of the Java API. Third party jars have no impact on that. And you can't change to the order because java.sql.Data is derived from java.util.Date. So the second must load before the first.
    And if you have two jar files with those classes in them (and not classes that use them) then you either should already know how to use them or you should stop trying to do whatever you are doing because it isn't going to work.

  • Java.util.Date badly serialized to java.sql.Timestamp Coherence 3.5.2

    Hi all,
    I'm running into this odd behaviour.
    I serialize java.util.Date objects to cache and when I read them back from cache, they appear to be java.sql.Timestamp types.
    I've isolated a junit test for that.
    Do you know why Coherence changes the type in the middle?
    Regards
    Harry.
    import java.util.Date;
    import org.junit.Assert;
    import org.junit.Test;
    import com.tangosol.io.Serializer;
    import com.tangosol.io.pof.ConfigurablePofContext;
    import com.tangosol.util.ExternalizableHelper;
    public class DatePofSerialTest {
         @Test
         public void testCobdate() throws Exception {
              Date date=new Date();
              Serializer serial = new ConfigurablePofContext();//"coherence-pof-config.xml");
              Date date2=(Date)ExternalizableHelper.fromBinary(ExternalizableHelper.toBinary(date, serial), serial);
              System.out.println(serial +" -- Date to serailize ["+ date.getClass() + "]");
              System.out.println(serial +" -- Date from deserialize ["+ date2.getClass() + "]");
              Assert.assertEquals(date, date2);/* Of course this passes, as both refer to the same time (long)*/
    {code}
    This gives as output
    {code:title=output |borderStyle=solid}
    log4j:WARN No appenders could be found for logger (Coherence).
    log4j:WARN Please initialize the log4j system properly.
    com.tangosol.io.pof.ConfigurablePofContext {location=coherence-pof-config.xml} -- Date to serailize [class java.util.Date]
    com.tangosol.io.pof.ConfigurablePofContext {location=coherence-pof-config.xml} -- Date from deserialize [class java.sql.Timestamp]
    {code}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Hi Harry,
    It looks like the same issue as ...
    PofExtractor with java.util.Date results in ClassCastException
    It was fixed in version 3.5.4.
    Thanks

  • How to combine sql.Date with sql.Time into one?

    I have a database where I keep dates and times separately, and getting date only and time only out of a java.util.Date is no problem thanks to the classes java.sql.Date and java.sql.Time. However, I need to read these values back in, put them back together, and then do date comparisons with java.util.GregorianCalendar. I tried just adding the millisecond long values together but that didn't seem to work, and I've tried setting the year, month, date, hours, minutes and seconds individually into a GregorianCalendar but I haven't figured that out yet. Certain queries work out better keeping the date and time separate in the database and it takes less bytes than a timestamp, so please don't suggest I use a timestamp!
    Thanks for your help!
    Stephen

    You can add the milliseconds (ms), but you need to use just part of it. For this example, let X be one more than the maximum number of units in time and also the minimum number of units in date. If we were using hours instead of ms X would be 24.
    t = total ms from time
    d = total ms from date
    T = new combined time
    T = ((d / X) * X) + (T % X);Add (the date, rounded to the nearest day) and (the portion of time which is less than a day).

  • (Again) java.util.Date vs java.sql.Date

    Hi there,
    (Again) Im trying to understand the EXACT difference between
    java.util.Date vs java.sql.Date.
    Googling, I can see that this is a very "popular" subject, but I still
    cannot figure out it exactly.
    Many writers claim that java.sql.Date only stores the DATE part (yyyy-
    mm-dd) but not the TIME part (hh:MM:ss) of a Date/Time value, but that
    I can easily disprove:
                    java.util.Date ud = new java.util.Date();                 java.sql.Date sd = new java.sql.Date(ud.getTime());                 System.out.println(DateFormatUtils.                                 format(ud, "yyyy-MM-dd HH:mm:ss.SSS"));                 System.out.println(DateFormatUtils.                                 format(sd, "yyyy-MM-dd HH:mm:ss.SSS"));
    Output:
                    2009-09-18 15:17:36.635                 2009-09-18 15:17:36.635
    So, apparently, java.sql.Date and java.util.Date have THE SAME
    precision (at least down to the millisecs...).
    And the official API documentation, really looks more confusing than
    helpful to me::
    *"java.sql.Date:*
    *A thin wrapper around a millisecond value that allows JDBC to identify*
    *this as an SQL DATE value. A milliseconds value represents the*
    *number of milliseconds that have passed since January 1, 1970*
    *00:00:00.000 GMT.*
    *To conform with the definition of SQL DATE, the millisecond values*
    *wrapped by a java.sql.Date instance must be 'normalized' by setting*
    *the hours, minutes, seconds, and milliseconds to zero in the*
    *particular time zone with which the instance is associated. "*
    Exactly what means "an SQL DATE value" ? How EXACTLY does it differ
    from a java.util.Date value?
    Most importantly: WHY does JDBC need to distinguish between them?
    And, here again: *"a java.sql.Date instance must be 'normalized' by*
    *setting the hours, minutes, seconds, and milliseconds to zero in the*
    *particular time zone..."*
    What does that mean exactly? Apparently, the constructor doesnt
    enforce this restriction, per the example above. So what's the REAL
    point with this type, java.sql.Date?
    Very greatful, if you can help me clarify this, once and for all.
    TIA,

    And the official API documentation, really looks more confusing than helpful to me:The problem is that you need to understand SQL as well as Java for this to make sense. It's not the Java API's job to tell you how your SQL database works - there's a myriad of subtle differences even when the DB is compliant with the SQL spec.
    Most compliant databases support DATE, TIME, and TIMESTAMP values. DATE represents only a date. TIME represents only a time. TIMESTAMP represents both. There are further complicating factors, but that's roughly how it stands.
    In Java the normal type for representing time is (or was when the API was created) the java.util.Date but this is a close approximation only to the TIMESTAMP value. In order to bring the two together the java.sql.Date, java.sql.Time and java.sql.Timestamp classes were created. Making them derive from java.util.Date was probably not a good idea.
    java.util.Date suffers from a number of deficiencies. java.util.Calendar was supposed to address them but didn't really succeed. The JodaTime library is rather better, but it's all a lot more complicated than you might expect - partly because time management really is a much harder problem than it appears at first glance - there are timezones, leap years, leap seconds, the difference between astronomical and atomic time, and so on and so forth.

  • How to change a date value from "java.util.Date" to "java.sql.Date"?

    Hi all,
    How to change a date value from "java.util.Date" to "java.sql.Date"?
    I m still confusing what's the difference between them.....
    thanks
    Regards,
    Kin

    Thanks
    but my sql statement can only accept the format (yyyy-MM-dd)
    such as "select * from xx where somedate = '2004-12-31'
    but when i show it to screen, i want to show it as dd-MM-yyyy
    I m using the following to change the jave.util.Date to str and vice versa. But it cannot shows the dd-MM-yyyy. I tried to change the format from yyyy-MM-dd to dd-MM-yyyy, it shows the wrong date in my application.
         public String date2str(java.util.Date thisdate)     {
              if (thisdate != null)     {
                   java.sql.Date thissDate = new java.sql.Date(thisdate.getTime());
                   return date2str(thissDate);
              }     else     {
                   return "";
         public String date2str(java.sql.Date thisdate)     {
              if (thisdate != null)     {
                   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                   return sdf.format(thisdate);
              }     else     {
                   return "";
         public java.util.Date str2date(String thisdate)     {
              String dateFormat = "yyyy-MM-dd"; // = 1998-12-31
              java.util.Date returndate = null;
              if (thisdate != null)     {
                   SimpleDateFormat dateFormatter = new SimpleDateFormat(dateFormat);
                   try {
                        returndate = dateFormatter.parse(thisdate);
                   } catch (ParseException pe) {
                        System.out.println (pe.getMessage());
              return returndate;
         }

  • Utility data collection job Failure on SQL server 2008

    Hi,
    I am facing data collection job failure issue (Utility-data Collection) on SQL server 2008 server for, below is the error message as  :
    <service Name>. The step did not generate any output.  Process Exit Code 5.  The step failed.
    Job name is collection_set_5_noncached_collect_and_upload, as I gothrough the google issue related to premission issue but where exactly the access issues are coimng, this job is running on proxy account. Thanks in advance.

    Hi Srinivas,
    Based on your description, you encounter the error message after configuring data collection in SQL Server 2008. For further analysis, could you please help to collect detailed log information? You can check the job history to find the error log around the
    issue, as is mentioned in this
    article. Also please check Data Collector logs by right-clicking on Data Collection in the Management folder and selecting View Logs.
    In addition, as your post, the exit code 5 is normally a ‘Access is denied ’ code.  Thus please make sure that the proxy account has admin permissions on your system. And ensure that SQL Server service account has rights to access the cache folder.
    Thanks,
    Lydia Zhang

  • Cannot convert from java.util.Date to java.sql.Date

    In the below code am trying to get the current date and 60 days prior date:
    Date  todayDate;
              Date  Sixtydaysprior;
              String DATE_FORMAT = "MM/dd/yy";
              DateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
             Calendar cal = Calendar.getInstance();
              todayDate = sdf.parse(sdf.format(cal.getTime()));
              cal.add(Calendar.DATE, -60);
             Sixtydaysprior = sdf.parse(sdf.format(cal.getTime()));I have imported following files:
    <%@page
         import="java.util.Calendar,
                   java.text.SimpleDateFormat,
                   java.text.ParseException,
                            java.util.*"
    %>Shows up following error msg:
    Type mismatch: cannot convert from java.util.Date to java.sql.Date
    Thanks.
    Edited by: MiltonDetroja on May 22, 2009 11:03 AM

    Shows up following error msg:
    Type mismatch: cannot convert from java.util.Date to java.sql.Date
    I don't think this exception is thrown from the portion of code you have shown. As clearly specified in exception message, you cannot cast an instance of java.util.Date to java.sql.Date. you will need to do something like this
    java.util.Date today = new java.util.Date();
    long t = today.getTime();
    java.sql.Date dt = new java.sql.Date(t);

  • Java.util.Date and java.sql.Date

    when i am trying to displaying date in my jsp page errors occurs saying that java.util.date and java.sql.date are matching..
    i have some sql statements which i need to execute in the page.so i cant delete that import sql statement.
    so what is the solution for this.
    i want to display the date as 19th april 2003....in the jsp page.
    thank u

    You should use full names.
    java.util.Date date;
    java.sql.Date sdate;
    ..And it may be a good idea to delete one of the two "import" declaration of packages.

  • Oracle (SQL) support for Temporal / time period based data

    Beyond standard SQL (DATE type etc. and <,>, LEAST, GREATEST, etc.) does Oracle offer anything to help handle time period based data? E.g. overlapping periods, joins when gaps in time periods from 2+ tables, period contiguity checks, etc. I've developed various SQL query techniques, but they're all rather cumbersome using standard SQL.
    Oracle Spatial offers geo-location support - is there anything similar for temporal query support?
    Any good books / docs on the subject?

    Check out Workspace manager for limited out of the box temporal support.
    You may also want to have a read through this series of articles about temporal database systems. They aren't Oracle specific, but may help you with your temporal system design.

  • Problem in converting util date format to sql date format

    im trying to convert util date to sql date...i'm getting the error msg as
    Error is : java.lang.NullPointerException
    Error Message : null
    i'm not bale to track the result...whatz the problem with this code?
    This fromDate value will be dynamically built, value will be
    fromDate="Tue Jul 15 00:00:00 IST 2003";
    java.util.Date xx=util.stringToDate(fromDate);
    java.sql.Date sqlD=null;
    sqlD.setTime(xx.getTime());
    System.out.println("sqld"+sqlD);

    I try this and it works:
    SimpleDateFormat simpledateformat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.UK);
    String s = "Tue Jul 15 00:00:00 IST 2003";
    java.util.Date date = simpledateformat.parse(s);
    java.sql.Date sqlD=new java.sql.Date(date.getTime());
    System.out.println("sqld"+sqlD);
    Hope this helps.

  • Convert java.sql.Date to java.util.Date

    How do i convert a java.sql.Date to java.util.Date ?
    SimpleDateFormat formatter = new SimpleDateFormat ("dd/MM/yy HH:mm");
    Date received=myresultset.getDate(1);
    String utildate = formatter.format(received);
    <%=utildate%>
    Result : doesn't keep the HH:mm format
    14/03/04 00:00
    Ideas ?

    There is simple way to do this job...
    java.util.Date utilDate = new java.util.Date();
    java.sql.Data sqlDate = new java.sql.Date(utilDate.getTime())
    Enjoy Coding ! ! ! ! !

  • Discussion - Date/Time POJO property - String or java.util.Date

    Hi,
    I always wonder how date/time should be declared in POJOs - String or java.util.Date. I have used both and always felt comfortable with String but still would like to know your views. (In DB datatype is datetime).
    I know some of you will say "as per requirement" but what I have experienced we never give too much thought and when we have issues down the line we start wondering.

    I always wonder how date/time should be declared in POJOs - String or java.util.Date. I have used both and always felt comfortable with String but still would like to know your views.
    (In DB datatype is datetime).If the latter is a given, then I would definitely use a Date. Doing the Date/String conversion at the DAO level seems an improper location; in particular, it constrains what upper layers can do with it:
    - if the business logic has to do date/time computation, it will have to convert back to Date (or Joda DateTime)
    - if the UI needs a different representation than the one that was used in the DAO (such as, different time zone, or showing only the month, whatever,...) it will probably need such a conversion too, and another one for the reformatting (or clumsy code parsing the date string).
    I know some of you will say "as per requirement" but what I have experienced we never give too much thought and when we have issues down the line we start wondering.I can easily see the issues caused by premature conversion to String. But what kind of issues do you risk if you keep the Date representation?
    In summary, I'm all in favor of using a Date (or Joda DateTime ) all along, until it's eventually displayed.
    Regards,
    J.

Maybe you are looking for

  • Striped + Mirrored software RAID no longer mounting

    I have a MacPro 4,1 using the 4 internal bays each with a 1.5GB drive. Drives 1&2 are mirrored, drives 3&4 are mirrored. Those 2 mirrored drives are then striped together for a volume called 'Titanic.' Been working great for years, but just recently

  • Blocked my account on Skype after breaking my akku...

    Hello! My account is blocked! Akkuant customer service has been restored but I can not call anyone! money in the account is! (about 10 euros) asking you to unblock my account. respect ....... dvov13

  • Installation failed exit code 34 error DW051

    Exit Code: 34 Please see specific errors and warnings below for troubleshooting. For example,  ERROR: DW051 ... -------------------------------------- Summary -------------------------------------- - 1 fatal error(s), 1 error(s), 0 warning(s) ERROR:

  • Detect end of last slide with JavaScript or JQuery (HTML5)

    Is there any way to detect when the last slide has completed playing, using JavaScript or JQuery? I am publishing as HTML5, if that matters.

  • Is there a way to supplement the download with the box?

    Having successfully claimed, downloaded and installed the complimentary Photoshop 13 ("CS6") for having bought Photoshop 12.x in April, is there a way to obtain the install DVD in the box for CS6 at a nominal or at least reasonable cost? During the c