Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

MySQL - Java date values

Options
  • 11-03-2005 6:28pm
    #1
    Registered Users Posts: 3,012 ✭✭✭


    Hi,
    trying to use java to insert data into a mysql database, but I one of the fields is a DATETIME object, and I dont know how to get java to generate this.

    Can anyone tell me how to do this?

    Cheers.


Comments

  • Registered Users Posts: 4,003 ✭✭✭rsynnott


    BizzyC wrote:
    Hi,
    trying to use java to insert data into a mysql database, but I one of the fields is a DATETIME object, and I dont know how to get java to generate this.

    Can anyone tell me how to do this?

    Cheers.

    Assuming you're using a Date object, do "date.getTime()". This gives you the number of seconds since 1970. Then insert it using something like this: "INSERT INTO <table>(<datetime field>) VALUES(FROM_UNIXTIME(<result of above))" There are more graceful ways to do it, but that one will work provided you don't need to go before 1970, and means you don't have to mess with the horrible GregorianCalendar class.
    Rob.


  • Registered Users Posts: 68,317 ✭✭✭✭seamus


    rsynnott wrote:
    Assuming you're using a Date object, do "date.getTime()". This gives you the number of seconds since 1970; as far as I remember MySQL is willing to accept this as a proper date. If not, you may have to mess with the GregorianCalendar class.
    Rob.
    Yep. DATETIME types should accept a timestamp (System.currTimeMilis() * 1000) as a valid value.


  • Registered Users Posts: 217 ✭✭Callan


    java.util.Date date = new java.util.Date();

    will also work


  • Registered Users Posts: 4,003 ✭✭✭rsynnott


    Of course, if you want the CURRENT date/time, all you need to do is INSERT <blah, blah> VALUES(NOW())

    (Always assuming that your MySQL server's clock is semi-accurate; was using a free MySQL DB service who's clock was SIX MONTHS wrong recently...)
    Rob


  • Registered Users Posts: 3,012 ✭✭✭BizzyC


    Cheers guys.

    Got it working.


  • Advertisement
  • Closed Accounts Posts: 248 ✭✭comanche


    should you not be using setTimeStamp?


  • Closed Accounts Posts: 92 ✭✭tempest


    comanche wrote:
    should you not be using setTimeStamp?

    Not for Statement objects. For Prepared or Callable Statements then yes,


Advertisement