📜  差之间的Java Java.sql.Timestamp和Java.sql.Date在Java中

📅  最后修改于: 2021-09-11 04:09:44             🧑  作者: Mango

在整个软件项目中,我们在许多情况下都使用Java.sql.Time、 Java.sql.Timestamp 和Java.sql.Date。每当Java应用程序与数据库交互时,我们应该使用它们而不是Java.util.Date。原因是 JDBC 即Java数据库连接使用这些来识别 SQL 日期和时间戳。

在这里,让我们通过几个例子来看看这三者之间的区别以及它们的用法:

java.sql.Time                                java.sql.Timestamp                              java.sql.Date                                     

Stores hours, minutes. Seconds and milliseconds alone.

Not stores date components and hence apt representation for SQL Time

Stores both Date and Time components

Stores years, months and days alone. 

Not stores time components and hence apt representation for SQL Date

This is dependent and extend java.util.Date This is dependent and extends java.util.Date This is independent and does not extend java.util.Date
As not having Date information, Date information is normalized and can be set to 0 to confirm ANSI SQL DATE As having both Date and Time, explicitly they are given As not having Time information, Time information is normalized and can be set to 0 to confirm ANSI SQL Time
Need to have 2 columns one for java.sql.Date and java.sql.Time explicitly. In comparison with java.util.Date, as it is not storing nanosecond details though Date and Time info present, equals method between java.sql.Timestamp and java.util.Date return false only. Only one column is enough to have both Date and Time.Nanosecond difference is much helpful in many scenarios from Java, setTimestamp() method is used to set the timestamp If we use the timestamp as datatype, using DATE() function, we can extract date alone, and using TIME() function, we can extract time alone.  Need to have 2 columns one for java.sql.Date and java.sql.Time explicitly from Java, setDate() method is used to set the date.
Just to know about the time value of the occurrence of the action. i.e. whether student available at that time on any day etc.,

This is the biggest advantage. In Java, we can write the below queries and get the Date and Time part respectively as follows : 

–To get Date 

select DATE() from  

–To get Time 

select TIME() from  

For logging entries, to know about the absolute value of transactional timings, we can use the timestamp

Just to know about the date value of the occurrence of the action. i.e. whether student available on that day

可以认为,既然Java.sql.Timestamp 可以满足同时存储Date 和Time 的需求,那还需要Java.sql.Date 和Java.sql.Time。让我们详细了解它们的场景

示例 1:在学校、学院、工作场所中,无论在何处查找学生/员工在特定日期是否有空,单独保留Java.sql.Date 就足够了

插入查询:

insert into empOrStuInformation(empOrStuName,empOrStuAvailability) values('xxx',now());
insert into empOrStuInformation(empOrStuName,empOrStuAvailability) values('yyy',now()); 
insert into empOrStuInformation(empOrStuName,empOrStuAvailability) values('zzz',now());

now() 以字符串返回配置时区中的当前日期和时间,但由于我们将 DATE 作为数据类型,因此我们将日期单独作为插入值。

输出:

Java
import java.sql.Date;
public class GFG {
    public static void main(String[] args)
    {
        String empOrStuAvailableDate = "2021-01-01";
        Date utilAvailabilityDate
            = new SimpleDateFormat("yyyy-MM-dd")
                  .parse(empOrStuAvailableDate);
        // jdbc connectivity expects java.sql.Date
        java.sql.Date sqlAvailabilityDate
            = new java.sql.Date(
                utilAvailabilityDate.getTime());
  
        try {
            Class.forName("com.mysql.jdbc.Driver");
  
            // Here test is the databasename
            // username is root and password is root
            Connection con = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/test", "root",
                "root");
  
            PreparedStatement pStmt = con.prepareStatement(
                "insert into empOrStuInformation (empOrStuName,empOrStuAvailability) values(?,?)");
            
            // As we are using Date datatype, we are using
            // setDate only...
            pStmt.setString(1, "AAAA");
            
            // The setDate() method is used to set date
            // while setTimestamp() is used to set time.
            pStmt.setDate(2, sqlAvailabilityDate);
            pStmt.executeUpdate();
            pStmt.close();
            con.close();
        }
        catch (Exception ex) {
            System.out.println(ex);
        }
    }
}


Java
import java.sql.Date;
import java.sql.Timestamp;
public class GFG {
    public static void main(String[] args)
    {
        String empOrStuAvailableDate = "2021-01-01";
        Date utilAvailabilityDate
            = new SimpleDateFormat("yyyy-MM-dd")
                  .parse(empOrStuAvailableDate);
        
        // jdbc connectivity expects java.sql.Date
        java.sql.Date sqlAvailabilityDate
            = new java.sql.Date(
                utilAvailabilityDate.getTime());
  
        // create a java timestamp object that represents
        // the current time (i.e., a "current timestamp")
        Calendar calendarInstance = Calendar.getInstance();
        
        java.sql.Timestamp sampleJavaTimestampObject
            = new java.sql.Timestamp(
                calendarInstance.getTime().getTime());
        try {
            Class.forName("com.mysql.jdbc.Driver");
            
            // Here test is the databasename
            // username is root and password is root
            Connection con = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/test", "root",
                "root");
  
            PreparedStatement pStmt = con.prepareStatement(
                "insert into empOrStuInformation1 (empOrStuName,empOrStuAvailability,empOrStuLogEntry) values(?,?,?)");
              
            // As we are using Date datatype, we are using
            // setDate only...
            pStmt.setString(1, "AAAA");
            
            // The setDate() method is used to set date
            pStmt.setDate(2, sqlAvailabilityDate);
            
            // setTimestamp() is used to set time.
            pStmt.setTimestamp(3,
                               sampleJavaTimestampObject);
            pStmt.executeUpdate();
            pStmt.close();
            con.close();
        }
        catch (Exception ex) {
            System.out.println(ex);
        }
    }
}


Java
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
public class GFG {
    public static void main(String[] args)
    {
        String empOrStuAvailableDate = "2021-01-01";
        Date utilAvailabilityDate
            = new SimpleDateFormat("yyyy-MM-dd")
                  .parse(empOrStuAvailableDate);
        // jdbc connectivity expects java.sql.Date
        java.sql.Date sqlAvailabilityDate
            = new java.sql.Date(
                utilAvailabilityDate.getTime());
  
        // create a java timestamp object that represents
        // the current time (i.e., a "current timestamp")
        Calendar calendarInstance = Calendar.getInstance();
        java.sql.Timestamp sampleJavaTimestampObject
            = new java.sql.Timestamp(
                calendarInstance.getTime().getTime());
        try {
            
            Class.forName("com.mysql.jdbc.Driver");
            
            // Here test is the databasename
            // username is root and password is root
            Connection con = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/test", "root",
                "root");
            
            // Instantiating the Time class
            Time entryTime = new Time(0L);
            
            // Setting time
            entryTime.setTime(
                new java.util.Date().getTime());
            PreparedStatement pStmt = con.prepareStatement(
                "insert into empOrStuInformation2(empOrStuName,empOrStuAvailability,empOrStuLogEntry,empOrStuEntryTime) values(?,?,?,?)");
  
            pStmt.setString(1, "AAAA");
            
            // The setDate() method is used to set date
            pStmt.setDate(2, sqlAvailabilityDate);
            
            // setTimestamp() is used to set timestamp.
            pStmt.setTimestamp(3, sampleJavaTimestampObject);
            
            // setTime() is used to set time.
            pStmt.setTime(4, entryTime);
  
            pStmt.executeUpdate();
            pStmt.close();
            con.close();
        }
        catch (Exception ex) {
            System.out.println(ex);
        }
    }
}


输出:

Java的.sql.Timestamp:

Java.sql.Timestamp 列对于记录条目非常有帮助。例如:学生/员工什么时候到达和离开处所,什么时候交记录,什么时候完成工作等等,

在 Mysql 中,我们可以通过以下方式为包含时间戳的列创建表。

Java

import java.sql.Date;
import java.sql.Timestamp;
public class GFG {
    public static void main(String[] args)
    {
        String empOrStuAvailableDate = "2021-01-01";
        Date utilAvailabilityDate
            = new SimpleDateFormat("yyyy-MM-dd")
                  .parse(empOrStuAvailableDate);
        
        // jdbc connectivity expects java.sql.Date
        java.sql.Date sqlAvailabilityDate
            = new java.sql.Date(
                utilAvailabilityDate.getTime());
  
        // create a java timestamp object that represents
        // the current time (i.e., a "current timestamp")
        Calendar calendarInstance = Calendar.getInstance();
        
        java.sql.Timestamp sampleJavaTimestampObject
            = new java.sql.Timestamp(
                calendarInstance.getTime().getTime());
        try {
            Class.forName("com.mysql.jdbc.Driver");
            
            // Here test is the databasename
            // username is root and password is root
            Connection con = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/test", "root",
                "root");
  
            PreparedStatement pStmt = con.prepareStatement(
                "insert into empOrStuInformation1 (empOrStuName,empOrStuAvailability,empOrStuLogEntry) values(?,?,?)");
              
            // As we are using Date datatype, we are using
            // setDate only...
            pStmt.setString(1, "AAAA");
            
            // The setDate() method is used to set date
            pStmt.setDate(2, sqlAvailabilityDate);
            
            // setTimestamp() is used to set time.
            pStmt.setTimestamp(3,
                               sampleJavaTimestampObject);
            pStmt.executeUpdate();
            pStmt.close();
            con.close();
        }
        catch (Exception ex) {
            System.out.println(ex);
        }
    }
}

输出:

拥有时间戳的优势之一是:

  1. 如果我们想要获取日期,那么我们可以写为select DATE(empOrStuLogEntry) from empOrStuInformation1
  2. 如果我们想得到时间,那么我们可以写为select TIME(empOrStuLogEntry) from empOrStuInformation1

Java的.sql.TIME

通过 mysql 插入语句:

输出:

Java

import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
public class GFG {
    public static void main(String[] args)
    {
        String empOrStuAvailableDate = "2021-01-01";
        Date utilAvailabilityDate
            = new SimpleDateFormat("yyyy-MM-dd")
                  .parse(empOrStuAvailableDate);
        // jdbc connectivity expects java.sql.Date
        java.sql.Date sqlAvailabilityDate
            = new java.sql.Date(
                utilAvailabilityDate.getTime());
  
        // create a java timestamp object that represents
        // the current time (i.e., a "current timestamp")
        Calendar calendarInstance = Calendar.getInstance();
        java.sql.Timestamp sampleJavaTimestampObject
            = new java.sql.Timestamp(
                calendarInstance.getTime().getTime());
        try {
            
            Class.forName("com.mysql.jdbc.Driver");
            
            // Here test is the databasename
            // username is root and password is root
            Connection con = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/test", "root",
                "root");
            
            // Instantiating the Time class
            Time entryTime = new Time(0L);
            
            // Setting time
            entryTime.setTime(
                new java.util.Date().getTime());
            PreparedStatement pStmt = con.prepareStatement(
                "insert into empOrStuInformation2(empOrStuName,empOrStuAvailability,empOrStuLogEntry,empOrStuEntryTime) values(?,?,?,?)");
  
            pStmt.setString(1, "AAAA");
            
            // The setDate() method is used to set date
            pStmt.setDate(2, sqlAvailabilityDate);
            
            // setTimestamp() is used to set timestamp.
            pStmt.setTimestamp(3, sampleJavaTimestampObject);
            
            // setTime() is used to set time.
            pStmt.setTime(4, entryTime);
  
            pStmt.executeUpdate();
            pStmt.close();
            con.close();
        }
        catch (Exception ex) {
            System.out.println(ex);
        }
    }
}

输出:

结论:

取决于要求,所有 3 个功能都有帮助。 Java.sql.Date -> 用于记录发生、进入、退出等,不考虑准确时间。 Java.sql.Time -> 无论日期如何都保持警报类型的功能, Java.sql.Timestamp-> 完美地记录条目,这对于找到表中出现的每个条目的性质非常有帮助,因此对恢复很有帮助。使用 Date() 和 Time() 函数,我们还可以明确地将日期部分和时间部分分开。