Inserting value in SQL Server’s datetime by java.sql.Timstamp

public static Timestamp getTodayTimestamp ()
{
java.util.Date date = null;
java.sql.Timestamp timeStamp = null;
try
{
Calendar calendar=Calendar.getInstance();
calendar.setTime(new Date());
java.sql.Date dt = new java.sql.Date(calendar.getTimeInMillis());
java.sql.Time sqlTime=new java.sql.Time(calendar.getTime().getTime());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
date = simpleDateFormat.parse(dt.toString()+" "+sqlTime.toString());
timeStamp = new java.sql.Timestamp(date.getTime());
}
catch (ParseException pe)
{
}
catch (Exception e)
{
}
return timeStamp;
}
Related Posts Plugin for WordPress, Blogger...
This entry was posted in Java.

7 thoughts on “Inserting value in SQL Server’s datetime by java.sql.Timstamp

  1. Hi

    that works a treat… thanks very much…

    dates are a pain … and dates between java and sql are worse…

    this code did the business for me thanks

  2. Uh….according to the javadoc for java.sql.Timestamp the ToString function returns a String object in yyyy-mm-dd hh:mm:ss.fffffffff format.

    So the sqlTime.toString() function should be sufficient, it works for me with mysql.

  3. Silly me, I see now that you are using the java.sql.Time and not Timestamp. I’m so used to seeing Timestamp I just glossed over that part. Good example of how to use the SimpleDateFormat. I never did understand how to use it just by looking at the javadoc.

  4. I think this code should be enough…


    public static Timestamp getTodayTimestamp ()
    {
    Calendar calendar=Calendar.getInstance();
    Timestamp timeStamp = new Timestamp(calendar.getTimeInMillis());
    return timeStamp;
    }

  5. I was able to post the current time to a MySql database using ODBC with just three statements:

    import java.util.*;
    import java.sql.Timestamp;

    try
    {
              Calendar thisCal=new GregorianCalendar();
              Timestamp startTime=new Timestamp(thisCal.getTimeInMillis());

    and then inserted into a PreparedStatement with

              ps.setTimestamp(FieldNum,startTime);

    } catch (Exception ex)
    {…

Leave a Reply

Your email address will not be published. Required fields are marked *