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

![](/files/-M9ko6g2dstBF0PHutxY)

&#x20;**Hey guy, Today I will show you how to use Date, Time, TimeStamp properly**&#x20;

### If you using only **Date** type&#x20;

so that the data type in the database is similar to data type in java then we should use the class **java.sql.Date**&#x20;

> *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.*

&#x20;

| 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.    |

&#x20;**Example** : get current date

```java
public class SQLDateExample {  
    public static void main(String[] args) {  
        long millis=System.currentTimeMillis();  
        java.sql.Date date=new java.sql.Date(millis);  
        System.out.println(date);  
    }  
}  
```

&#x20;**Example** : Set custom date&#x20;

```java
import java.sql.Date;  
public class StringToSQLDateExample {  
public static void main(String[] args) {  
    String str="2015-03-31";  
    Date date=Date.valueOf(str);//converting string into sql date  
    System.out.println(date);  
}  
}  
```

### If you using Datetime&#x20;

Then we should use the class **java.sql.Timestamp**&#x20;

> *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                                                                                                        |
| ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
| [after()](https://www.javatpoint.com/java-timestamp-after-method)         | Returns Boolean value true if this Timestamp object comes later than given Timestamp object.                       |
| [before()](https://www.javatpoint.com/java-timestamp-before-method)       | Returns Boolean value true if this Timestamp object comes earlier than given Timestamp object.                     |
| [compareTo()](https://www.javatpoint.com/java-timestamp-compareto-method) | Compares this Timestamp object to the given Timestamp object or to the given date object                           |
| [equals()](https://www.javatpoint.com/java-timestamp-equals-method)       | Returns a Boolean value true if this Timestamp object is equal specified object or to the given Timestamp object . |
| [from()](https://www.javatpoint.com/java-timestamp-from-method)           | Obtains an instance of Timestamp from an Instant object                                                            |
| [getNanos()](https://www.javatpoint.com/java-timestamp-getnanos-method)   | 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.     |

&#x20;**Example 1**&#x20;

```java
import java.sql.Timestamp;  
import java.time.Instant;  
public class JavaTimestampFromExample_1 {  
    public static void main(String[] args) {  
        //from() method Obtains an instance of Timestamp from an Instant object  
       Timestamp instant= Timestamp.from(Instant.now());  
        System.out.println("1. from() method will return "+instant);  
        // valueOf() method returns a Timestamp value corresponding to the given string  
        String str="2018-09-01 09:01:15";  
        Timestamp timestamp= Timestamp.valueOf(str);  
        System.out.println("2. value of Timestamp : "+timestamp);  
        //getNanos() method gets the Timestamp obejct's nanos value  
        Integer val=timestamp.getNanos();  
        System.out.println("3. Fractional seconds component : "+val);  
        Timestamp ts2 = Timestamp.valueOf("2018-09-01 09:01:16");  
        //before() returns Boolean value true if this ts1 comes earlier than given ts2  
        System.out.println("4. Boolean value returned : "+timestamp.before(ts2));  
    }  
}  
```

&#x20;**Example 2**&#x20;

```java
import java.sql.Timestamp;  
import java.time.Instant;  
public class JavaTimespanExample2 {  
    public static void main(String[] args) {  
        Timestamp ts1 = Timestamp.valueOf("2018-09-01 09:01:15");  
        System.out.println("Timestamp : "+ts1);  
        // getTime() method returns the number of milliseconds  
        Long val=ts1.getTime();  
        System.out.println("1. Milliseconds : "+val);  
        //hashCode() method returns the hash code for this object.  
        Integer val1=ts1.hashCode();  
        System.out.println("2. Hash code : "+val1);  
        // setNanos() method sets nanos value for the specified integer value.  
        ts1.setNanos(54647);  
        System.out.println("3. Timestamp after setting nanos : " + ts1);  
        // toInstant() method returns an Instant which represents the same point on the time-line as this Timestamp  
        Instant instant = ts1.toInstant();  
        System.out.println("4. Instant Timespan : " + instant);  
    }  
}  
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://pea-story.gitbook.io/pexpa/experience/how-to-using-date-time-timestamp-for-java-to-connect-database.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
