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

<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.12.5</version>
</dependency>

Maven Central

How do I use Joda-Time’s DateMidnight class?

The org.joda.time.DateMidnight class represent a date time information with the time value set to midnight. The following snippet show you how to instantiate this class.

package org.kodejava.joda;

import org.joda.time.DateMidnight;
import org.joda.time.format.DateTimeFormat;

public class DateMidnightDemo {
    public static void main(String[] args) {
        // Create DateMidnight object of the current system date.
        DateMidnight date = new DateMidnight();
        System.out.println("date = " + date);

        // Or using the now().
        date = DateMidnight.now();
        System.out.println("date = " + date);

        // Create DateMidnight object by year, month and day.
        date = new DateMidnight(2021, 10, 29);
        System.out.println("date = " + date);

        // Create DateMidnight object from milliseconds.
        date = new DateMidnight(System.currentTimeMillis());
        System.out.println("date = " + date);

        // Parse a date from string.
        date = DateMidnight.parse("2021-10-29");
        System.out.println("date = " + date);

        // Parse a date from string of specified patter.
        date = DateMidnight.parse("29/10/2021", 
                DateTimeFormat.forPattern("dd/MM/yyyy"));
        System.out.println("date = " + date);
    }
}

The result of our code snippet:

date = 2021-10-29T00:00:00.000+08:00
date = 2021-10-29T00:00:00.000+08:00
date = 2021-10-29T00:00:00.000+08:00
date = 2021-10-29T00:00:00.000+08:00
date = 2021-10-29T00:00:00.000+08:00
date = 2021-10-29T00:00:00.000+08:00

Maven Dependencies

<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.12.5</version>
</dependency>

Maven Central

How do I create DateTime object in Joda-Time?

The following example show you a various way to create an instance of Joda-Time’s DateTime class. By using the default constructor we will create an object with the current system date time. We can also create the object by passing the information like year, month, day, hour, minutes and second.

Joda can also use an instance from JDK’s java.util.Date and java.util.Calendar to create the DateTime. This means that the date object of JDK and Joda can be used to work together in our application.

package org.kodejava.joda;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;

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

public class DateTimeDemo {

    public static void main(String[] args) {
        // Creates DateTime object using the default constructor will
        // give you the current system date.
        DateTime date = new DateTime();
        System.out.println("date = " + date);

        // Or simply calling the now() method.
        date = DateTime.now();
        System.out.println("date = " + date);

        // Creates DateTime object with information like year, month,
        // day, hour, minute, second and milliseconds
        date = new DateTime(2021, 10, 29, 0, 0, 0, 0);
        System.out.println("date = " + date);

        // Create DateTime object from milliseconds.
        date = new DateTime(System.currentTimeMillis());
        System.out.println("date = " + date);

        // Create DateTime object from Date object.
        date = new DateTime(new Date());
        System.out.println("date = " + date);

        // Create DateTime object from Calendar object.
        Calendar calendar = Calendar.getInstance();
        date = new DateTime(calendar);
        System.out.println("date = " + date);

        // Create DateTime object from string. The format of the
        // string  should be precise.
        date = new DateTime("2021-10-29T06:30:00.000+08:00");
        System.out.println("date = " + date);
        date = DateTime.parse("2021-10-29");
        System.out.println("date = " + date);
        date = DateTime.parse("29/10/2021",
                DateTimeFormat.forPattern("dd/MM/yyyy"));
        System.out.println("date = " + date);
    }
}

The result of our code snippet:

date = 2021-10-29T06:30:01.068+08:00
date = 2021-10-29T06:30:01.147+08:00
date = 2021-10-29T00:00:00.000+08:00
date = 2021-10-29T06:30:01.148+08:00
date = 2021-10-29T06:30:01.148+08:00
date = 2021-10-29T06:30:01.166+08:00
date = 2021-10-29T06:30:00.000+08:00
date = 2021-10-29T00:00:00.000+08:00
date = 2021-10-29T00:00:00.000+08:00

Maven Dependencies

<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.12.5</version>
</dependency>

Maven Central

How do I create array of unique values from another array?

This code snippet show you how to create an array of unique numbers from another array of numbers.

package org.kodejava.lang;

import java.util.Arrays;

public class UniqueArray {
    /**
     * Return true if num appeared only once in the array.
     */
    public static boolean isUnique(int[] numbers, int num) {
        for (int number : numbers) {
            if (number == num) {
                return false;
            }
        }
        return true;
    }

    /**
     * Convert the given array to an array with unique values and
     * returns it.
     */
    public static int[] toUniqueArray(int[] numbers) {
        int[] temp = new int[numbers.length];
        // in case you have value of 0 in the array
        Arrays.fill(temp, -1);

        int counter = 0;
        for (int number : numbers) {
            if (isUnique(temp, number))
                temp[counter++] = number;
        }

        int[] uniqueArray = new int[counter];
        System.arraycopy(temp, 0, uniqueArray, 0, uniqueArray.length);
        return uniqueArray;
    }

    /**
     * Print given array
     */
    public static void printArray(int[] numbers) {
        for (int number : numbers) {
            System.out.print(number + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        int[] numbers = {1, 1, 2, 3, 4, 1, 4, 7, 9, 7};
        printArray(numbers);
        printArray(toUniqueArray(numbers));
    }
}

For other example to create unique array check the following example How do I remove duplicate element from array?.

How do I get attributes of element during SAX parsing?

This example show you how to get the attributes of elements in an XML file using the SAX parser.

package org.kodejava.xml;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.InputStream;

public class SAXElementAttribute {
    public static void main(String[] args) {
        SAXElementAttribute demo = new SAXElementAttribute();
        demo.run();
    }

    private void run() {
        try {
            // Create SAXParserFactory instance and a SAXParser
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();

            // Get an InputStream to the elements.xml file and parse
            // its contents using the SAXHandler.
            InputStream is =
                    getClass().getResourceAsStream("/elements.xml");
            DefaultHandler handler = new SAXHandler();
            parser.parse(is, handler);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    static class SAXHandler extends DefaultHandler {
        @Override
        public void startElement(String uri, String localName,
                                 String qName, Attributes attributes)
                throws SAXException {

            int attributeLength = attributes.getLength();
            if ("person".equals(qName)) {
                for (int i = 0; i < attributeLength; i++) {
                    // Get attribute names and values
                    String attrName = attributes.getQName(i);
                    String attrVal = attributes.getValue(i);
                    System.out.print(attrName + " = " + attrVal + "; ");
                }
                System.out.println();
            }
        }
    }
}

The elements.xml file is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <persons>
        <person name="Foo" age="25" />
        <person name="Bar" age="22" />
    </persons>
</root>