Using java.sql.Time: Offset by 1 hour?

I have a problem understanding the behaviour of the java.sql.Time class. As the following example shows.
61952000 ms is the Time 17:12:32. If i feed a Time-Object with it and print the time or date I'll get "18:12:32",
an offset of 1h. But if I use time.getTime(), I get my ms value which equals 17:12:32.
As my timezone shows, I have a GMT offset of one hour. But why does the getTime() method not calculate
the timezone offset to the ms?
Time time = new Time(61952000);
        System.out.println(time.getTime() / 3600 / 1000); // 17 hours
        System.out.println( new Date(time.getTime()) ); // Thu Jan 01 18:12:32 CET 1970
        System.out.println(time.getTime()); // 61952000
        System.out.println(time); // 18:12:32
        System.out.println(Calendar.getInstance().getTimeZone());
         *  sun.util.calendar.ZoneInfo[id="Europe/Berlin",offset=3600000,dstSavings=3600000,
         *  useDaylight=true,transitions=143,lastRule=java.util.SimpleTimeZone[id=Europe/Berlin,
         *  offset=3600000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,
         *  startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,
         *  endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]]
         */

Thanks for your reply. But please take a look at the following code snippet. It intends to add a Timestamp representing the
start of a day (time component 00:00:00) to a time component (having Date to 01-01-1970):
        Time time = new Time(61952000);
        Calendar c = Calendar.getInstance();
        System.out.println("time: " + time); // 18:12:32
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.MILLISECOND, 0);
        System.out.println("date: " + c.getTime()); // Fri Apr 03 00:00:00 CEST 2009
        Timestamp timestamp = new Timestamp( c.getTimeInMillis() + time.getTime() );
        Date d = new Date(timestamp.getTime() );
        System.out.println("\nresult: " + d); // result: Fri Apr 03 17:12:32 CEST 2009If I assume that getting and setting the milis always deals with timezone independent values, but operating methods
like toString(), getHour() etc use the timezone, then I can not explain the result (last line): 17:12:32 is the timezone
independend value. Should'nt d.toString() show the timezone dependend value of 18:12:32?

Similar Messages

  • Getting the current time using java.sql.Time

    I need to set the current time in a database field. I tried the following code (using my logic) to set the current time. But, I end up getting "Jan 1, 1970" in the time field in the database.
    Here is the code :
    Calendar cal = Calendar.getInstance();
    Java.sql.Time now = java.sql.Time.valueOf(
              cal.get(Calendar.HOUR_OF_DAY) + ":" +
              cal.get(Calendar.MINUTE) + ":" +
              cal.get(Calendar.SECOND));
    What should I do to get the current time in the "now" variable? Right now, it ends up in the database as "Jan 1, 1970".
    Thanx in advance.

    Can you show me the code to do SimpleDateFormat?
    Assuming that I use the following skeleton to get the
    time value from the database, can you show me the
    code for the missing link (so as to display in the
    format "hh:mm:ss") ?
    java.sql.Time timeFromDb =
    obj.getActionTime();
    // The above code gets the "time" field from
    the database into "timeFromDb"
    // Use SimpleDateFormat to display the time
    java.text.SimpleDateFormat sdf = new
    java.text.SimpleDateFormat("hh:mm:ss");
    // Now what do I do with "sdf" and
    "timeFromDb" ?
    // Print out the time value
    System.out.printf("Time is : %s\n",
    .... );Hi,
    I don't know if you want 24h clock or not. This is the pattern for 24h clock.
    "HH:mm:ss"
    You get the text string by calling sdf.format(timeFromDb)
    Kaj

  • Java.sql.Time not working correctly

    Hi guys,
    I have the following code which is used to put clients session data in my database.
    long logged_in_time = p.getCreatedTime();
                long logged_out_time = System.currentTimeMillis();
                long duration = logged_out_time - logged_in_time;
                System.out.println("LOGGED IN: " + logged_in_time);
                System.out.println("LOGGED OUT: " + logged_out_time);
                System.out.println("DURATION: " + duration);
                System.out.println("DURATION TIME: " + new Time(duration));and this is the result:
    LOGGED IN: 1141394617474
    LOGGED OUT: 1141394638634
    DURATION: 21160
    DURATION TIME: 01:00:21
    Does anyone know why java.sql.Time adds an hour? The duration in milliseconds equals 21 seconds but when I constuct the Time obj I get 1 hour 21 seconds.
    Any help would be great.
    Alex

    Probably because your default timezone is not GMT, but GMT+1 (e.g. CET.)
    The java.util.Date (and subclasses) wraps a long value representing the number of miliseconds elapsed since January 1, 1970, 00:00:00 GMT.
    As a consequence a new Date(0) will represent the date above, which is equivalent to January 1, 1970, 01:00:00 CET.
    You might use a DateFormat and specify the TimeZone.
    Example:        Time time = new Time(21160);
            DateFormat format = DateFormat.getTimeInstance();
            format.setTimeZone(TimeZone.getTimeZone("CET"));
            System.out.println(format.format(time));
            format.setTimeZone(TimeZone.getTimeZone("GMT"));
            System.out.println(format.format(time));Will output:
    01:00:21
    00:00:21

  • Get the difference between two java.sql.Time values

    Hi, I'm developping a web application in which I need to to subtract one java.sql,Time value from another. The two values are stored in a database field of type DateTime. I used following code
    java.sql.Time start_time=resultset.getTime("startTime");
    java.sql.Time end_time=resultset.getTime("startTime");
    java.sql.Time diff=start_time-end_time;
    can u give me any comment on this code

    Remember what the Date/Time object in Java represents - a single point in time.
    Subtracting one from another gives you an amount of time elapsed between the two dates. Fine.
    Making a new Date out of that number is incorrect. The number no longer represents a point in time, but rather a duration.
    Its like saying "There is 10 seconds difference between the two times, so the time is now 1 Jan 1970, 00:00:10 GMT".
    The simple and stupid calculation is to take the milliseconds difference, and divide it to get to a more humanly readable value.
    // duration in milliseconds
    long duration = ?????
    long durationInSeconds = duration / 1000;
    long durationInMinutes = duration / (60 * 1000);
    long durationInHours = duration / (60 * 60 * 1000);
    // careful - not always true!
    long durationInDays = duration / (24 * 60 * 60 * 1000);
    NOTE: The "daysBetween" calculation is potentially complicated by Daylight Time adjustments. The simple approach does not necessarily work exactly.
    Cheers,
    evnafets

  • Create table dinamically using java sql types?

    Hi! I've an application that reads an XML file. This file contains de definitions of some tables, using java sql types. For example:
    <dbtable>
      <dbtablename>Name of table</dbtablename>
      <dbtablefield>
        <name>Name of table field</name>
        <type>java.sql.Types.VARCHAR</type>
        <length>10</lenght>
        <canNull>0</canNull>
        <isPK>1</isPK>
      </dbtablefield>
    </dbtable>That's a little example of one table, with one field. Is a java.sql.Types.VARCHAR (or is equivalent in int), which has a size of 10, it cannot be null and is a primary key for the table.
    Now, the lenght, null, and primary keys are not problem at all. What I want to know, is how do I create de table using the java.sql.Types. I mean, I don't want to hard code:
    String s = "CREATE TABLE name (COLUMN VARCHAR(10)...";Instead, I want to use some "wild cards", as are used in PreparedStatement. The idea of this is that no matter what DB I'm using, I must always be capable of creating the tables not worrying for the DB. I mean, I must be able to create the table in Oracle, SQL Server, DB2, etc., using the same XML and the same java class.
    Something like:
    String s = "CREATE TABLE name (COLUMN ? (10)...";
    someobject.setObject(1,java.sql.Types.VARCHAR);
    someobject.execute(); //create tableIs this possible? Or do I have to make a map for each DB?
    Thanks a lot for your help! Dukes available!

    you can provide some fields at runtime..
    for example
    "CREATE TABLE name (COLUMN" + arg[1] +"(10)..."
    here arg is the string array passed into the main.

  • New java.sql.Time(3600000) = 02:00:00

    hi,
    i'm a little confused with time in java. everyone know that 3600000 millisecond = 01:00:00 (1h) so what is going on with this: new java.sql.Time(3600000) = 02:00:00 ?
    does anyone can help?

    Everyone also knows that the standard "stringification" of such an object provides you with the date/time in your timezone while the value relates to GMT. 01:00 GMT is 02:00 CET.

  • Converting String to java.sql.Time

    i have got a string like String time = "12:08 P.M.";
    I want to convert it to java.sql.Time .
    Please anyone suggest me the solution.

    CROSSPOST: http://forum.java.sun.com/thread.jspa?threadID=5162798&messageID=9621227
    A crosspost with only 2 postings. Is that a new record? Or does it just tie the record :-)

  • Overhead of using java.sql.STRUCT

    I am calling a stored proc passing in a java.sql.STRUCT
    created via DDL statement
    CREATE TYPE APPDBA.MY_STRUCT
    AS OBJECT
    USER_KEY INTEGER,
    USER_HOME VARCHAR2(32)
    My question is:
    when i am creating a structdescriptor from java
    oracle.sql.StructDescriptor sDesc =
    oracle.sql.StructDescriptor.createDescriptor ("APPDBA.MY_STRUCT", mConnection)
    what exactly goes on under the hood here? Does the driver
    make a round trip call to the DB every time?
    Does it do some sort of caching?
    Thanks.

    Thanks for your reply. But please take a look at the following code snippet. It intends to add a Timestamp representing the
    start of a day (time component 00:00:00) to a time component (having Date to 01-01-1970):
            Time time = new Time(61952000);
            Calendar c = Calendar.getInstance();
            System.out.println("time: " + time); // 18:12:32
            c.set(Calendar.HOUR_OF_DAY, 0);
            c.set(Calendar.SECOND, 0);
            c.set(Calendar.MINUTE, 0);
            c.set(Calendar.MILLISECOND, 0);
            System.out.println("date: " + c.getTime()); // Fri Apr 03 00:00:00 CEST 2009
            Timestamp timestamp = new Timestamp( c.getTimeInMillis() + time.getTime() );
            Date d = new Date(timestamp.getTime() );
            System.out.println("\nresult: " + d); // result: Fri Apr 03 17:12:32 CEST 2009If I assume that getting and setting the milis always deals with timezone independent values, but operating methods
    like toString(), getHour() etc use the timezone, then I can not explain the result (last line): 17:12:32 is the timezone
    independend value. Should'nt d.toString() show the timezone dependend value of 18:12:32?

  • How to use java.sql.Date ?

    hi there:
    I used
    ps.setDate(27, new java.sql.Date(new java.util.Date().getTime()));
    ps.executeUpdate();
    in my code to insert the current date to the 27th column of one table, this column's type is DATE, the database is ORACLE. However, I got the error like this one: ORA-01843: not a valid month.
    I think I incorrectly used the java.sql.Date API to cause this error. So anyone can tell me how to use it correctly?
    Thanks for the answers,
    Sway

    Other columns are all VARCHAR2 type;
    The oracle error message indicated that this is a
    date-related one. 27th are the only column using DATE
    So I came to draw my conclusion that the SQL might be
    wrong.Except that if, for example, the date column is actually at index 26 then Oracle might try to convert the string being passed in (at 26) as a date. But it isn't a date. So then oracle is going to throw an exception indicating that something is wrong - like that the month is invalid.

  • String conversion of time to Java.Sql.Time

    Hello,
    Im developing a servlet based application where I need to take the time from the user in the hh:mm format and then add it to the database ( MS SQL Server 2000) . I do so via a HTML page.
    Now in my servlet I retrieve the value using request.getParameter which gets retrieved as String.So now I need to convert it to the Time format so that I can add it to the DB.
    Can someone please guide me as to how this is done, Ive tried SimpleDateFormat but Im not quite clear with that concept and so I think Ive messed it up. Hence Im not posting anything here.
    Please help me out.
    Thanks in advance.
    null

    String dateStr = "15:00";
    SimpleDateFormat format = new SimpleDateFormat("HH:mm");
    try {
                Date date = format.parse(dateStr);
                System.out.println("date: " + date);
                Time t = new Time(date.getTime());
                System.out.println("date: " + date);
    } catch (ParseException e) {
    }

  • Need an information using java.sql in jsp

    I found that there is a 'dataset' like architecture in .NET, is there any 'dataset' like substance in our java, if it is means can you give me some ideas for using it in jsp, give me some example for saving a record in the mysql database. very urgent please,

    KIRUPA_SHANKAR wrote:
    I found that there is a 'dataset' like architecture in .NET, is there any 'dataset' like substance in our java, if it is means can you give me some ideas for using it in jsp, give me some example for saving a record in the mysql database. Shouldn't be doing database stuff in JSPs. Use JSTL and its <sql> tags if you must.
    RowSet might be close. I don't write .NET.
    very urgent please,Not to me.
    %

  • Using Java SQL

    Some help on this would be appreciated.
    Basically I have a program that reads from a list of strings and then performs some 'select' and 'delete' queries (with these string variables) on a sybase database. The problem I have is with the results set and 'getString(n)' class.
    I WILL POST SOME CODE IN A REPLY;
    The class checkVal runs a count on each table and returns true or false.
    If the value is zero that means there are no occurances of this ID
    (Variable label) and therefore do not have to be deleted from the table.
    I had to add the "(labelSource.equals("M_CTP_ID"))" for the tables with a different type of relationship.
    The first select statement gives an integer if you perform the statement from a command window but when I run the class checkVal it gives me 0.
    I've tried everything ( I hope not!!)
    The database is Sysbase.
    I'm using the "com.ddtek.jdbc.sybase.SybaseDriver" driver.
    Brian

    if (labelSource.equals("M_CTP_ID")){
    results = null;
    results = stmt.executeQuery( "select count(*) from " + sourceTable + " where " + labelSource + " = " + "(select M_ID from " + counterpartyField1.getText() + " where M_LABEL = " + label +")");     
    addtoLog("SQL: select count(*) from " + sourceTable + " where " + labelSource + " = " + "(select M_ID from " + counterpartyField1.getText() + " where M_LABEL = " + label +")" + newline, code);
    results.next();
    count = Integer.valueOf(results.getString(1)).intValue();
    else{
    results = null;
    results = stmt.executeQuery("select count(*) from " + sourceTable + " where " + labelSource + " = "+ label);
    addtoLog("SQL: select count(*) from " + sourceTable + " where " + labelSource + " = "+ label + newline, code);
    results.next();
    count = Integer.valueOf(results.getString(1)).intValue();
    }

  • USE OF VARRAY and RECORD object vis-a-vis java.sql package

    Hi Geeks,
    I want to pass an array of java objects to a stored procedure and I will use them for table insertion or updation.
    Say I have a table TASK at DataBase end while the same TASK object is there at JAVA end.
    I want to pass an array of Task objects via my stored proc
    Please guide me how shall I use java.sql.Array and java.sql.SQLDataType etc etc. any mechanism in store!..
    Regards,
    Pratap
    London

    Thanks for you help
    I created the package and I get this error this time:
    javax.servlet.ServletException: bean test not found within scope
         org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:822)
         org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:755)
         org.apache.jsp.login_jsp._jspService(login_jsp.java:68)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:94)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:268)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:277)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:223)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:856)

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

  • 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

Maybe you are looking for