Java - How to get current timestamps

In this section, we will show you examples to get the current date time or timestamp in Java.

1. Java Timestamp examples

The below program uses java.sql.Timestamp to get the current timestamp and format the display with SimpleDateFormat.

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

public class Main {

// 2023.01.23.00.40.49
private static final SimpleDateFormat simpleDateFormat1 =
new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");

// 2023-01-23T00:40:49.761+05:30
private static final SimpleDateFormat simpleDateFormat12 =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");

// 2023-01-23 00:40:49
private static final SimpleDateFormat simpleDateFormat13 =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

public static void main(String[] args) {

// method 1
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
System.out.println(timestamp);

// method 2 - via Date
Date date = new Date();
System.out.println(new Timestamp(date.getTime()));

// number of milliseconds since January 1, 1970, 00:00:00 GMT
System.out.println(timestamp.getTime());

System.out.println(simpleDateFormat1.format(timestamp));

System.out.println(simpleDateFormat12.format(timestamp));

System.out.println(simpleDateFormat13.format(timestamp));

}
}


Console Output:
2023-01-23 00:40:49.761
2023-01-23 00:40:49.762
1674414649761
2023.01.23.00.40.49
2023-01-23T00:40:49.761+05:30
2023-01-23 00:40:49

2. Convert Instant to/from Timestamp

This example shows how to convert the java.time.Instant to the java.sql.Timestamp.

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

public class Main {

public static void main(String[] args) {

Timestamp timestamp = new Timestamp(System.currentTimeMillis());
System.out.println(timestamp);
System.out.println(timestamp.getTime());

// Convert Timestamp to Instant
Instant instant = timestamp.toInstant();
System.out.println(instant);
System.out.println(instant.toEpochMilli());

// Convert Instant to Timestamp
Timestamp tsFromInstant = Timestamp.from(instant);
System.out.println(tsFromInstant.getTime());

}
}


Console Output:
2023-01-23 00:47:25.838
1674415045838
2023-01-22T19:17:25.838Z
1674415045838
1674415045838


More topics,

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete