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

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

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

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

  • 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

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

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

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

  • 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

  • Datasource, POJO and java.sql.Blob

    Hello,
    is "java.sql.Blob" a valid type for a POJO datasource ?
    I declared one but I just dit not succeed in rendering its jpg picture.
    My java code is quite simple :
    ReportClientDocument reportClientDocument = new ReportClientDocument ();
    reportClientDocument.setReportAppServer(ReportClientDocument.inprocConnectionString);
    reportClientDocument.open (REPORT_NAME, OpenReportOptions._openAsReadOnly);
    // lBlob is a class which implements java.sql.Blob interface
    LPOJOData [] dataP = {new LPOJOData(new lBlob("Picture.jpg"))};
    POJOResultSetFactory factory = new POJOResultSetFactory(LPOJOData.class);
    POJOResultSet resultSet = factory.createResultSet(dataP);
    reportClientDocument.getDatabaseController().setDataSource(resultSet, "", "");
    and my POJO class :
    public class LPOJOData {          
              private java.sql.Blob zimage;
              public LPOJOData(java.sql.Blob zp){
                   this.zimage = zp;
              public java.sql.Blob getzimage(){
                   return zimage;
    The field "zimage" on the report is designed through a "field definition only" database, zimage is defined as a Blob field.
    Any clues ?
    Regards,
    Serge

    I have just found a list of the data types supported by a POJO Class :
    # boolean
    # byte
    # char
    # double
    # float
    # int
    # short
    # java.lang.Boolean
    # java.lang.Byte
    # java.lang.Double
    # java.lang.Float
    # java.lang.Integer
    # java.lang.Short
    # java.lang.String
    # java.SQL.Date
    # java.SQL.Time
    Well, java.SQL.Blob is not one of them.
    Is java.SQL_Blob will be a valid POJO type in the future ?
    Is there another way than POJO to feed a report from an in-memory datasource ?

  • How to get java.sql.Timestamp data from database

    Hello, i'm new to EJB and i can't get java.sql.Timestamp data, but when i'm trying to get java.lang.String data it works fine.
    * @ejb.finder
    * query="SELECT OBJECT(c) FROM userSCHEMA AS c
    *      WHERE c.lastName LIKE ?1
    * AND c.firstName LIKE ?2
    * AND c.registeredDate < ?3"
    * signature="java.util.Collection findPatient * (java.lang.String lastName,
    * java.lang.String firstName,
    * java.sql.Timestamp)"
    <method-params>
    <method-param>java.lang.String</method-param>
    <method-param>java.lang.String</method-param>
    <method-param>java.sql.Timestamp</method-param>
    </method-params>
    Where i made a mistake ?

    The main problem that I'm faced with, is that the
    java.sql.Timestamp now has only one constructor, it
    takes "long", i.e., milliseconds.That's because a Timestamp is just an offset from a particular instant of time. It doesn't have a timezone.
    Please note that I'm not trying to "print", i.e., I'm
    not interested in using the SimpleDateFormat.Then what are you interested in? You appear to be trying to create a Timestamp with a particular timezone, which doesn't make sense as I already noted. Is there a reason for this?

  • Usage of java.sql.Timestamp with classes12.zip and ojdbc14.jar  ?

    Hi all,
    If i'm using java.sql.Timestamp with classes12 it is functioning perfectly,
    if i'm using ojdbc14 and java.sql.Timestamp it is functioning in different way and failing to do the action..
    Example : update set xxx=yy where time = my Timestamp object set in Prepared statement
    Hope to see the answer

    http://forum.java.sun.com/thread.jspa?threadID=460615&messageID=2116517
    Timestamp insert problem
    Using the "classes12.zip" file that comes with the distribution for Oracle versions 8.1.6.x and 8.1.7.x, Oracle's DATE datatype is mapped to the "java.sql.Timestamp" class. However, the "ojdbc14.jar" driver maps DATE to "java.sql.Date", and "java.sql.Date" only holds a date (without a time), whereas "java.sql.Timestamp" holds both a date and a time.

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

  • Making java.sql.Date dd.mm.yyyy format

    Hi,
    java.sql.Date format is m/d/yyyy.
    I must use  dd.mm.yyyy format.
    How can it be done?
    Thanks.

    You can use the following line of code to change the date format
    SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy");
    String formattedDate = formatter.format(<Ur java.sql.Date instance>);
    Edited by: Santhosh Edla on Sep 7, 2009 5:00 PM

Maybe you are looking for