Java how to save both date and time in the database __ database

Source: Internet
Author: User
Tags date now dateformat locale

How Java can store dates and times in the database at the same time

Default classification 2009-04-23 12:20:46 reading 244 Comments 0 Font Size: Big Small Subscribe

SQL Server has a data type datetime that holds the format of date + time, such as:
1900-1-1 16:36:44.000
If you want to make the 1900-1-1 16:36:44 in the database (that is, the DateTime field above), you can generate the corresponding date data by transformation.
The data inserted into the database must be the date of the Java.sql.Date type, so you can save the database by converting the string to the Java.sql.Date type date, similar to the one above.
Here's a class that will change the string 1900-1-1 16:36:44 to a java.sql.Date type.
Import java.text.*;
Import Java.util.Locale;
public class Stringtodate {
  public final static java.sql.Date String2date (String datestring)
  Throws Java.lang.Exception {
    dateformat dateformat;
    DateFormat = new SimpleDateFormat ("Yyyy-mm-dd kk:mm:ss", locale.english);
    dateformat.setlenient (false);
    java.util.Date timedate = Dateformat.parse (datestring);//util type
    Java.sql.Date dateTime = new Java.sql.Date (Timedate.gettime ());//sql type
    return dateTime;
 }
}


Method Two
SimpleDateFormat sdf = new SimpleDateFormat ("Yyyy-mm-dd kk:mm:ss");
        java.util.Date now = new Java.util.Date ();
        String resultdate = Sdf.format (now);
        Java.util.Date last = new Java.util.Date (resultdate);
.....
Psmt.setdate (i, New Java.sql.Date (last));

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.