How to using Date, Time, TimeStamp for Java to connect Database

Hey guy, Today I will show you how to use Date, Time, TimeStamp properly

If you using only Date type

so that the data type in the database is similar to data type in java then we should use the class java.sql.Date

The java.sql.Date class represents only date in java. It inherits java.util.Date class.

The java.sql.Date instance is widely used in JDBC because it represents the date that can be stored in database.

Some constructors and methods of java.sql.Date class has been deprecated. Here, we are not giving list of any deprecated constructor and method.

No.

Method

Description

1

void setTime(long time)

changes the current sql date to given time.

2

Instant toInstant()

converts current sql date into Instant object.

3

LocalDate toLocalDate()

converts current sql date into LocalDate object.

4

String toString()

converts this sql date object to a string.

5

static Date valueOf(LocalDate date)

returns sql date object for the given LocalDate.

6

static Date valueOf(String date)

returns sql date object for the given String.

Example : get current date

Example : Set custom date

If you using Datetime

Then we should use the class java.sql.Timestamp

Timestamp provides formatting and parsing operations to support JDBC escape syntax. It also adds the ability to hold the SQL TIMESTAMP fractional seconds value.

Methods

Description

Returns Boolean value true if this Timestamp object comes later than given Timestamp object.

Returns Boolean value true if this Timestamp object comes earlier than given Timestamp object.

Compares this Timestamp object to the given Timestamp object or to the given date object

Returns a Boolean value true if this Timestamp object is equal specified object or to the given Timestamp object .

Obtains an instance of Timestamp from an Instant object

Fetches the Timestamp object's nanos value

getTime()

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT

hashCode()

Returns a hash code value for this object

setNanos()

Sets a nanos value for the specified integer value

setTime()

Sets this class's object to indicate a point in time (milliseconds) after January 1, 1970 00:00:00 GMT

toInstant()

Coverts the Timespan object to an Instant which represents the same point on the time-line as this Timestamp

toLocalDateTime()

Converts this Timespan object to a LocalDateTime which represents the same date-time value as this Timestamp

toString()

Converts the Timespan object in JDBC timestamp escape format

valueOf()

Converts the string object to Timestamp value or obtains an instance of Timestamp from a LocalDateTime object.

Example 1

Example 2

Last updated

Was this helpful?