java.sql.Timestamp Examples

The java.sql.Timestamp extends java.util.Date class. java.sql.Timestamp is used in the JDBC API, as a wrapper around java.util.Date that handles SQL specific requirements. This class exists to represent SQL TIMESTAMP, which able to keep date and time. Similar to java.sql.Date and java.sql.Time, java.sql.Timestamp should be used only when working with databases, like to set a timestamp on a java.sql.PreparedStatement, get a timestamp from a java.sql.ResultSet, working with java.sql.SQLData, etc.

Getting java.sql.Timestamp Instance

We can instantiate a java.sql.Timestamp object using following constructor:

SqlTimestampInitExample.java
import java.sql.Timestamp;

public class SqlTimestampInitExample {
    
    public static void main(String[] args) {
        long now = System.currentTimeMillis();
        Timestamp sqlTimestamp = new Timestamp(now);
        System.out.println("currentTimeMillis     : " + now);
        System.out.println("SqlTimestamp          : " + sqlTimestamp);
        System.out.println("SqlTimestamp.getTime(): " + sqlTimestamp.getTime());
    }
}
                    

Which will produce (result may vary) :

currentTimeMillis     : 1564061013564
SqlTimestamp          : 2019-07-25 21:23:33.564
SqlTimestamp.getTime(): 1564061013564

Or, you can use static valueOf(...) methods to get an instance of java.sql.Timestamp object

  • static Timestamp valueOf​(String s): Converts a String object in JDBC timestamp escape format to a Timestamp value.
  • static Timestamp valueOf​(LocalDateTime dateTime): Obtains an instance of Timestamp from a LocalDateTime object, with the same year, month, day of month, hours, minutes, seconds and nanos date-time value as the provided LocalDateTime. This static method available for Java 8 and above.
SqlTimestampValueOfExample.java
import java.sql.Timestamp;
import java.time.LocalDateTime;

public class SqlTimestampValueOfExample {
    
    public static void main(String[] args) {
        Timestamp sqlTimestamp1 = Timestamp.valueOf("1983-07-12 21:30:55.888");
        System.out.println("SqlTimestamp1: " + sqlTimestamp1);
        
        Timestamp sqlTimestamp2 = Timestamp.valueOf(LocalDateTime.of(1980, 4 , 9, 8, 15, 20, 345000000));
        System.out.println("SqlTimestamp2: " + sqlTimestamp2);
    }
}
                    

SqlTimestamp1: 1983-07-12 21:30:55.888
SqlTimestamp2: 1980-04-09 08:15:20.345

Another method (which is available since Java 8) is from(...):

SqlTimestampFromToIntantExample.java
import java.sql.Timestamp;
import java.time.Instant;

public class SqlTimestampFromToIntantExample {
    
    public static void main(String[] args) {
        Instant instant1 = Instant.now();
        Timestamp sqlTimestamp = Timestamp.from(instant1);
        System.out.println("sqlTimestamp: " + sqlTimestamp);
        
        Instant instant2 = sqlTimestamp.toInstant();
        System.out.println("instant     : " + instant2);
    }
}
                    

which will result (may vary):

sqlTimestamp: 2019-07-26 00:09:02.241
instant     : 2019-07-25T16:09:02.241Z

Method toInstant() used to convert Timestamp object to an Instant.

Timestamp's Nanoseconds

One advantage in the java.sql.Timestamp from its superclass java.util.Date is its ability to hold the nanoseconds (which Date is only able to hold until milliseconds only). You can get and set the nanoseconds using the getNanos() and setNanos().

  • int getNanos(): Gets this Timestamp object's nanos value.
  • void setNanos(int n): Sets this Timestamp object's nanos field to the given value.

SqlTimestampGetSetNanosExample.java
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SqlTimestampGetSetNanosExample {
    
    public static void main(String[] args) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        
        long now = System.currentTimeMillis();
        Date date = new Date(now);
        System.out.println("date              : " + df.format(date));
        System.out.println();
        
        Timestamp sqlTimestamp = new Timestamp(now);
        System.out.println("sqlTimestamp      : " + sqlTimestamp);
        System.out.println("sqlTimestamp nanos: " + sqlTimestamp.getNanos());
        System.out.println();
        
        sqlTimestamp.setNanos(123456789);
        System.out.println("sqlTimestamp      : " + sqlTimestamp);
        System.out.println("sqlTimestamp nanos: " + sqlTimestamp.getNanos());
        System.out.println();
    }
}
                    

date              : 2019-07-26 00:47:06.405

sqlTimestamp      : 2019-07-26 00:47:06.405
sqlTimestamp nanos: 405000000

sqlTimestamp      : 2019-07-26 00:47:06.123456789
sqlTimestamp nanos: 123456789

In above example, Date able to get 405 as milliseconds, but Timestamp able to get 405000000 as nanoseconds. Timestamp also able to maintain 123456789 nanoseconds for every digits.

Comparing Timestamps

There are several methods available for comparison:

  • boolean after(Timestamp ts): Indicates whether this Timestamp object is later than the given Timestamp object.
  • boolean before(Timestamp ts): Indicates whether this Timestamp object is earlier than the given Timestamp object.
  • int compareTo(Timestamp ts): Compares this Timestamp object to the given Timestamp object.
  • int compareTo(Date o): Compares this Timestamp object to the given Date object.
  • boolean equals(Object ts): Tests to see if this Timestamp object is equal to the given object.
  • boolean equals​(Timestamp ts): Tests to see if this Timestamp object is equal to the given Timestamp object.

There is also hashCode() that comes in pair with equals(...) methods.

SqlTimestampComparisonExample.java
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;

public class SqlTimestampComparisonExample {
    
    public static void main(String[] args) {
        long now = System.currentTimeMillis();
        Timestamp sqlTimestamp1 = new Timestamp(now);
        System.out.println("sqlTimestamp1            : " + sqlTimestamp1);

        Timestamp sqlTimestamp2 = new Timestamp(324126010345L);
        System.out.println("sqlTimestamp2            : " + sqlTimestamp2);
        System.out.println("sqlTimestamp2 nanoseconds: " + sqlTimestamp2.getNanos());
        System.out.println();
        
        System.out.println("sqlTimestamp1 after sqlTimestamp2    : " + sqlTimestamp1.after(sqlTimestamp2));
        System.out.println("sqlTimestamp2 after sqlTimestamp1    : " + sqlTimestamp2.after(sqlTimestamp1));

        System.out.println("sqlTimestamp1 before sqlTimestamp2   : " + sqlTimestamp1.before(sqlTimestamp2));
        System.out.println("sqlTimestamp2 before sqlTimestamp1   : " + sqlTimestamp2.before(sqlTimestamp1));
        
        System.out.println("sqlTimestamp1 compareTo sqlTimestamp2: " + sqlTimestamp1.compareTo(sqlTimestamp2));
        System.out.println("sqlTimestamp2 compareTo sqlTimestamp1: " + sqlTimestamp2.compareTo(sqlTimestamp1));
        System.out.println();
        
        Calendar cal = Calendar.getInstance();
        cal.set(1980, 3, 9, 18, 30, 10);
        cal.set(Calendar.MILLISECOND, 345);
        Date date1 = cal.getTime();
        System.out.println("Date1                        : " + date1);
        System.out.println("sqlTimestamp2 compareTo date1: " + sqlTimestamp2.compareTo(date1)); 
        System.out.println();
        
        Date date = new Date(now);  // similar with sqlTimestamp1 from currentTimeMillis
        System.out.println("Date2                             : " + date);
        System.out.println("sqlTimestamp1 equals object       : " + sqlTimestamp1.equals(date));  
        
        Object obj = sqlTimestamp2.clone();
        System.out.println("Object                            : " + obj);
        System.out.println("sqlTimestamp2 equals object       : " + sqlTimestamp2.equals(obj));        
        
        Timestamp sqlTimestamp3 = new Timestamp(((Timestamp) obj).getTime());
        System.out.println("sqlTimestamp2 equals sqlTimestamp3: " + sqlTimestamp2.equals(sqlTimestamp3)); 
    }
}
                    

Result (may vary):

sqlTimestamp1            : 2019-07-26 01:30:44.753
sqlTimestamp2            : 1980-04-09 18:30:10.345
sqlTimestamp2 nanoseconds: 345000000

sqlTimestamp1 after sqlTimestamp2    : true
sqlTimestamp2 after sqlTimestamp1    : false
sqlTimestamp1 before sqlTimestamp2   : false
sqlTimestamp2 before sqlTimestamp1   : true
sqlTimestamp1 compareTo sqlTimestamp2: 1
sqlTimestamp2 compareTo sqlTimestamp1: -1

Date1                                : Wed Apr 09 18:30:10 SGT 1980
sqlTimestamp2 compareTo sqlTimestamp1: 0

Date2                             : Fri Jul 26 01:30:44 SGT 2019
sqlTimestamp1 equals object       : false
Object                            : 1980-04-09 18:30:10.345
sqlTimestamp2 equals object       : true
sqlTimestamp2 equals sqlTimestamp3: true

Another Methods

  • long getTime(): Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Timestamp object.
  • void setTime(long time): Sets this Timestamp object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT.
  • LocalDateTime toLocalDateTime(): Converts this Timestamp object to a LocalDateTime.
  • String toString(): Formats a timestamp in JDBC timestamp escape format.

And similar with java.sql.Date and java.sql.Time, since java.sql.Timestamp extends java.util.Date, so java.util.Date methods also available for java.sql.Timestamp.

SqlTimestampMethodsExample.java
import java.sql.Timestamp;
import java.time.LocalDateTime;

public class SqlTimestampMethodsExample {
    
    public static void main(String[] args) {
        long now = System.currentTimeMillis();
        Timestamp sqlTimestamp = new Timestamp(now);
        // implicitely call sqlTimestamp.toString()
        System.out.println("SqlTimestamp          : " + sqlTimestamp);
        
        sqlTimestamp.setTime(461196920875L);
        System.out.println("SqlTimestamp          : " + sqlTimestamp);
        System.out.println("SqlTimestamp.getTime(): " + sqlTimestamp.getTime());
        
        LocalDateTime localDt = sqlTimestamp.toLocalDateTime();
        System.out.println("LocalDateTime         : " + localDt);
    }
}
                    

SqlTimestamp          : 2019-07-26 01:44:49.097
SqlTimestamp          : 1984-08-13 06:15:20.875
SqlTimestamp.getTime(): 461196920875
LocalDateTime         : 1984-08-13T06:15:20.875

Conclusion

The java.sql.Time inherits from java.util.Date, and able to keeps both date and time until nanoseconds granularity. On another hand, we already learn earlier that java.sql.Date keeps date only, and java.sql.Time keeps time component only. So, if working with database and we need to keep both date and time, we must use java.sql.Timestamp.