How do I get date and time fields of DateTime object in Joda-Time?

In Joda-Time the date and time information are divided into fields. The following example show you some fields that can be obtained from the DateTime object. For example to get the day of the year we use the getDayOfYear() method and to get the day of week we can use the getDayOfWeek() method.

package org.kodejava.example.joda;

import org.joda.time.DateTime;

public class DateTimeFieldDemo {
    public static void main(String[] args) {
        DateTime dateTime = new DateTime();
        System.out.println("dateTime = " + dateTime);

        // Get day of year, day of month, day of week and week of
        // year of a date.
        System.out.println("DOY = " + dateTime.getDayOfYear());
        System.out.println("DOM = " + dateTime.getDayOfMonth());
        System.out.println("DOW = " + dateTime.getDayOfWeek());
        System.out.println("WOW = " + dateTime.getWeekOfWeekyear());

        // Get hour of day, minute of hour and second of minute.
        System.out.println("HOD = " + dateTime.getHourOfDay());
        System.out.println("MOH = " + dateTime.getMinuteOfHour());
        System.out.println("SOM = " + dateTime.getSecondOfMinute());

        // Get minute of day and second of day.
        System.out.println("MOD = " + dateTime.getMinuteOfDay());
        System.out.println("SOD = " + dateTime.getSecondOfDay());
    }
}

The outputs of our program are:

dateTime = 2017-01-16T09:43:36.662+08:00
DOY = 16
DOM = 16
DOW = 1
WOW = 3
HOD = 9
MOH = 43
SOM = 36
MOD = 583
SOD = 35016

Maven Dependencies

<!-- http://repo1.maven.org/maven2/joda-time/joda-time/2.9.7/joda-time-2.9.7.jar -->
<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.9.7</version>
</dependency>

Wayan Saryada

Programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply