How do I convert Joda-Time’s DateTime into Calendar or Date object?

This code snippet show you how to convert Joda-Time’s DateTime object into JDK’s java.util.Calendar or java.util.Date object. To convert DateTime to java.util.Date we use the toDate() method and to convert to java.util.Calendar we use the toCalendar() method.

package org.kodejava.joda;

import org.joda.time.DateTime;

import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class DateTimeToDateCalendarDemo {
    public static void main(String[] args) {
        // Converting DateTime object into JDK's Date.
        DateTime dateTime = DateTime.now();
        Date date = dateTime.toDate();
        System.out.println("org.joda.time.DateTime = " + dateTime);
        System.out.println("java.util.Date         = " + date);

        // Converting DateTime object into JDK's Calendar.
        Calendar calendar = dateTime.toCalendar(Locale.getDefault());
        System.out.println("java.util.Calendar     = " + calendar);
    }
}

The result of our code snippet:

org.joda.time.DateTime = 2021-10-29T06:54:29.003+08:00
java.util.Date         = Fri Oct 29 06:54:29 CST 2021
java.util.Calendar     = java.util.GregorianCalendar[time=1635461669003,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=31,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2021,MONTH=9,WEEK_OF_YEAR=44,WEEK_OF_MONTH=5,DAY_OF_MONTH=29,DAY_OF_YEAR=302,DAY_OF_WEEK=6,DAY_OF_WEEK_IN_MONTH=5,AM_PM=0,HOUR=6,HOUR_OF_DAY=6,MINUTE=54,SECOND=29,MILLISECOND=3,ZONE_OFFSET=28800000,DST_OFFSET=0]

Maven Dependencies

<!-- https://search.maven.org/remotecontent?filepath=joda-time/joda-time/2.10.14/joda-time-2.10.14.jar -->
<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.10.14</version>
</dependency>

Maven Central

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.