Java : java.util.Date and java.sql.Timestamp Conversion


java.sql.Timestamp is subclass of java.util.Date. java.sql.Timestamp  allows the JDBC API to identify this as an SQL TIMESTAMP value. It hold the SQL TIMESTAMP fractional seconds value, by allowing the specification of fractional seconds to a precision of nanoseconds. A Timestamp also provides formatting and parsing operations to support the JDBC escape syntax for timestamp values.
The precision of a Timestamp object is calculated to be either:
Precision 19 :yyyy-mm-dd hh:mm:ss
Precision 20 + s: yyyy-mm-dd hh:mm:ss.[fff…] and s represents the scale of the given Timestamp, its fractional seconds precision.

Note: This type is a composite of a java.util.Date and a separate nanoseconds value. Only integral seconds are stored in the java.util.Date component. The fractional seconds – the nanos – are separate.

Example

package com.date;

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

public class DateSQLTimestampConversion {

public static void main(String[] args) {
Date date = new Date();
System.out.println("Java Util Date : " + date);

// Converting java.util.Date to java.sql.Timestamp
Timestamp timestamp = new Timestamp(date.getTime());
System.out.println("Java SQL Timestamp : " + timestamp);

// Convert java.sql.Timestamp to java.util.Date
Date newDate = new Date(timestamp.getTime());
System.out.println("Java Util Date : " + date);
}

}

Output


Java Util Date : Mon Jul 30 11:35:27 PDT 2018
Java SQL Timestamp : 2018-07-30 11:35:27.246
Java Util Date : Mon Jul 30 11:35:27 PDT 2018

Reference

https://docs.oracle.com/javase/8/docs/api/java/sql/Timestamp.html

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s