Java Convert Timestamp to Calendar

Tags: Java Timestamp Java Calendar

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

How to convert Timestamp to Calendar in Java

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

  • Using the Timestamp.getTime() method to return epoch milliseconds value which is the number of milliseconds since January 1, 1970, 00:00:00 GMT.
  • Create a new instance of Calendar object and using the Calendar.setTimeInMillis(long millis) method to set epoch milliseconds value to Calendar object.

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

ConvertTimestampToCalendarExample1.java

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

public class ConvertTimestampToCalendarExample1 {
    public static void main(String... args) {
        // Create new Timestamp object as current time
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());

        // Convert Timestamp object to Calendar object
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(timestamp.getTime());

        System.out.println("Timestamp: " + timestamp);
        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));
    }
}
The output as below.
Timestamp: 2022-05-18 23:05:15.894
Calendar year: 2022
Calendar month (JANUARY is 0): 4
Calendar day of month: 18
Calendar hour: 23
Calendar minute: 5
Calendar second: 15
Calendar millisecond: 894

Happy Coding 😊

Java Convert Date to Timestamp

Java Convert Timestamp to Date

Java Convert Calendar to Timestamp

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