Thursday 26 March 2020

How to get java.sql.TimeStamp in Java?

There are multiple way to get an instance of Timestamp.

Approach 1: Using Timestamp constructor.
Timestamp timeStamp1 = new Timestamp(System.currentTimeMillis());
Timestamp timeStamp2 = new Timestamp(2020, 1, 9, 14, 49, 11, 627);

Approach 2: Using java.util.Date.
Date date = new Date();
Timestamp timeStamp3 = new Timestamp(date.getTime());

Approach 3: Using Instant.
Instant instant = date.toInstant();
Timestamp timeStamp4 = Timestamp.from(instant);

Approach 4: Using LocalDateTime.
LocalDateTime localDateTime = LocalDateTime.now();
Timestamp timeStamp5 = Timestamp.valueOf(localDateTime);

App.java
package com.sample.app;

import java.util.Date;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDateTime;

public class App {

  public static void main(String args[]) {
    Timestamp timeStamp1 = new Timestamp(System.currentTimeMillis());
    
    Timestamp timeStamp2 = new Timestamp(2020, 1, 9, 14, 49, 11, 627);
    
    Date date = new Date();
    Timestamp timeStamp3 = new Timestamp(date.getTime());
    
    Instant instant = date.toInstant();
    Timestamp timeStamp4 = Timestamp.from(instant);
    
    LocalDateTime localDateTime = LocalDateTime.now();
    Timestamp timeStamp5 = Timestamp.valueOf(localDateTime);
    
    System.out.println(timeStamp1);
    System.out.println(timeStamp2);
    System.out.println(timeStamp3);
    System.out.println(timeStamp4);
    System.out.println(timeStamp5);

  }

}

Output
2020-01-09 14:56:09.344
3920-02-09 14:49:11.000000627
2020-01-09 14:56:09.349
2020-01-09 14:56:09.349
2020-01-09 14:56:09.415

You may like
Previous                                                    Next                                                    Home

No comments:

Post a Comment