$show=/label

Java 8 - How to convert Calendar to LocalDateTime?

SHARE:

A quick example to convert Calendar Object to LocalDateTime in Java 8. LocalDateTime.ofInstant() is used to convert Calendar to LocalDateTime Object.

1. Overview

In this article, You'll learn how to convert Calendar to LocalDateTime object in java 8 DateTime api

LocalDateTime api can be used completely replacement to the Date class as all features of Date functions are done in a simple and precise way such as adding minutes to the current date.

Java 8 - How to convert Calendar to LocalDateTime?



2. Example Program To Convert Calendar to LocalDateTime

To convert to LocalDateTime, you need to do the following steps.

Step 1:

First, Create a Calendar instance using Calendar.getInstance() method that returns Calendar object.

Step 2 :

Next, Get the time zone from the calendar instance using the calendar.getTimeZone() method.

Step 3:

Now, Get the ZoneId object from TimeZone class using timezone.toZoneId() method.

Step 4:

Finally, Invoke the LocalDateTime.ofInstant(calendar.toInstant(), zoneId) method with the calendar instant and zone id value.

package com.javaprogramto.java8.dates.conversion;

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

public class CalenderToLocalDateTimeExample {

    public static void main(String[] args) {

        //Create a calender instance.
        Calendar calendar = Calendar.getInstance();

        System.out.println("Calender instance : "+calendar);

        // Getting the timezone
        TimeZone tz = calendar.getTimeZone();

        // Getting zone id
        ZoneId zoneId = tz.toZoneId();

        // conversion
        LocalDateTime localDateTime = LocalDateTime.ofInstant(calendar.toInstant(), zoneId);

        System.out.println("Local date time object  : "+localDateTime);

    }
}
Output:
Calender instance : java.util.GregorianCalendar[time=1596972628333,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Kolkata",offset=19800000,dstSavings=0,useDaylight=false,transitions=7,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2020,MONTH=7,WEEK_OF_YEAR=33,WEEK_OF_MONTH=3,DAY_OF_MONTH=9,DAY_OF_YEAR=222,DAY_OF_WEEK=1,DAY_OF_WEEK_IN_MONTH=2,AM_PM=1,HOUR=5,HOUR_OF_DAY=17,MINUTE=0,SECOND=28,MILLISECOND=333,ZONE_OFFSET=19800000,DST_OFFSET=0]
Local date time object  : 2020-08-09T17:00:28.333

3. Convert Calendar to LocalDate

package com.javaprogramto.java8.dates.conversion;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;

public class CalenderToLocalDateExample {

    public static void main(String[] args) {

        Calendar cal = Calendar.getInstance();
        Date input = cal.getTime();
        LocalDate la = input.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

        System.out.println("Calender to LocalDate : "+la);
    }
}

Output:
Calender to LocalDate : 2020-08-09

4. Single Line Conversion from Calendar to LocalDateTime and LocalDate in Java 8


Finally, You can get the conversion to LocalDateTime and LocalDate in Java 8 in a single line. It is good practice to write in separate methods for reusing.
package com.javaprogramto.java8.dates.conversion;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Calendar;

public class SingleLineCalenderToLocalDateTimeExample {

    public static void main(String[] args) {

        //Create a calender instance.
        Calendar calendar = Calendar.getInstance();


        LocalDateTime singleLineLocalDateTime = getLocalDateTime(calendar);
        LocalDate singleLineLocalDate = getLocalDate(calendar);

        System.out.println("Converted LocalDateTime : "+singleLineLocalDateTime);
        System.out.println("Converted LocalDate : "+singleLineLocalDate);

    }

    private static LocalDateTime getLocalDateTime(Calendar calendar){

        return  LocalDateTime.ofInstant(calendar.toInstant(), calendar.getTimeZone().toZoneId());
    }

    private static LocalDate getLocalDate(Calendar calendar){

        return  LocalDateTime.ofInstant(calendar.toInstant(), calendar.getTimeZone().toZoneId()).toLocalDate();
    }
}
Output:
Converted LocalDateTime : 2020-08-09T20:23:47.780
Converted LocalDate : 2020-08-09

5. Conclusion


In this article, You've learned how to convert Calendar Date object into LocalDateTime and LocalDate in Java 8.

And also can be converted LocalDateTime to LocalDate using toLocalDate() method.

Examples programs shown are in the GitHub.




COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,16,Arrays,16,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,23,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,84,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,12,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,10,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,30,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,77,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,93,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Conversions,3,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Logging,1,Mac OS,2,Math,1,Matrix,5,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,23,String,58,String Programs,12,String Revese,1,Swing,1,System,1,Tags,1,Threads,10,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java 8 - How to convert Calendar to LocalDateTime?
Java 8 - How to convert Calendar to LocalDateTime?
A quick example to convert Calendar Object to LocalDateTime in Java 8. LocalDateTime.ofInstant() is used to convert Calendar to LocalDateTime Object.
https://1.bp.blogspot.com/-nqYAYVxyCgs/XzARc9ciTwI/AAAAAAAAC4s/C25CvsiONpQrJe65trfJeRmKV9lI2t26wCLcBGAsYHQ/w640-h365/%2BJava%2B8%2B-%2BHow%2Bto%2Bconvert%2BCalendar%2Bto%2BLocalDateTime%253F.png
https://1.bp.blogspot.com/-nqYAYVxyCgs/XzARc9ciTwI/AAAAAAAAC4s/C25CvsiONpQrJe65trfJeRmKV9lI2t26wCLcBGAsYHQ/s72-w640-c-h365/%2BJava%2B8%2B-%2BHow%2Bto%2Bconvert%2BCalendar%2Bto%2BLocalDateTime%253F.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/08/how-to-convert-calendar-to-localdatetime-in-java-8.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/08/how-to-convert-calendar-to-localdatetime-in-java-8.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content