Java Convert Calendar to Timestamp

Tags: Java Calendar Java Timestamp

In this Java core tutorial we learn how to convert a java.util.Calendar object to a java.sql.Timestamp object in Java programming language.

How to convert Calendar to Timestamp in Java

In Java program, with a given Calendar object we can follow these steps to convert it to Timestamp object.

  • Using the Date.getTimeInMillis() method to return epoch milliseconds value which is the number of milliseconds since January 1, 1970, 00:00:00 GMT.
  • Using the Timestamp(long time) constructor to instantiate a new Timestamp object from epoch milliseconds value.

In the following example Java code we show how to convert Calendar object to Timestamp object using the steps above.

ConvertCalendarToTimestampExample1.java

import java.sql.Timestamp;
import java.util.Calendar;

public class ConvertCalendarToTimestampExample1 {
    public static void main(String... args) {
        Calendar calendar = Calendar.getInstance();

        // Convert Calendar object to Timestamp object
        Timestamp timestamp = new Timestamp(calendar.getTimeInMillis());

        System.out.println("Calendar year: " + calendar.get(Calendar.YEAR));
        System.out.println("Calendar month (JANUARY is 0): " + calendar.get(Calendar.MONTH));
        System.out.println("Calendar day of month: " + calendar.get(Calendar.DAY_OF_MONTH));
        System.out.println("Calendar hour: " + calendar.get(Calendar.HOUR_OF_DAY));
        System.out.println("Calendar minute: " + calendar.get(Calendar.MINUTE));
        System.out.println("Calendar second: " + calendar.get(Calendar.SECOND));
        System.out.println("Calendar millisecond: " + calendar.get(Calendar.MILLISECOND));
        System.out.println("Timestamp: " + timestamp);
    }
}
The output as below.
Calendar year: 2022
Calendar month (JANUARY is 0): 4
Calendar day of month: 18
Calendar hour: 23
Calendar minute: 11
Calendar second: 41
Calendar millisecond: 183
Timestamp: 2022-05-18 23:11:41.183

Happy Coding 😊

Java Convert Date to Timestamp

Java Convert Timestamp to Date

Java Convert Timestamp to Calendar

Java Convert Timestamp to ZonedDateTime

Java Convert Timestamp to LocalDate

Java Convert Timestamp to Instant

Java Convert Timestamp to OffsetDateTime

Java Convert OffsetDateTime to Timestamp