Convert LocalDateTime to java.util.Calendar Object in Java


Below are steps to convert the Java LocalDateTime object into java.util.Calendar object,


Step 1: We will create an object of Java 8 Date-Time API LocalDateTime class.

LocalDateTime localDateTime = LocalDateTime.now();

Step 2: Next, we will create an object of ZoneId that will be required to convert LocalDate time to ZonedDateTime.

ZoneId zoneId = ZoneId.systemDefault();

Step 3: We now convert LocalDateTime to ZonedDateTime object

ZonedDateTime zonedDateTime = localDateTime.atZone(zoneId);

Step 4:We create an instance of Calendar class.

Calendar calendar = Calendar.getInstance();

Step 5: Finally we get the epoch time in milliseconds from zonedDateTime and set it to calendar object.

calendar.setTimeInMillis(zonedDateTime.toInstant().toEpochMilli());

Complete Code:

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Calendar;

public class LocalDateTimeToCalendarExample {

    public static void main(String[] args) {

        LocalDateTime now = LocalDateTime.now();
        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime zonedDateTime = now.atZone(zoneId);
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(zonedDateTime.toInstant().toEpochMilli());

    }
}


References:

-

Facing issues? Have Questions? Post them here! I am happy to answer!


Author Info:

Rakesh (He/Him) is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap