How do I use Joda-Time’s Instant Class?

An instant in the datetime continuum specified as a number of milliseconds from 1970-01-01T00:00Z. Some classes that represent an instance in the Joda-Time library includes the Instant, DateTime, DateMidnight and MutableDateTime classes.

package org.kodejava.example.joda;

import org.joda.time.DateTime;
import org.joda.time.Instant;

public class InstantDemo {
    public static void main(String[] args) {
        // An instant in the datetime continuum specified as
        // a number of milliseconds from 1970-01-01T00:00Z.
        //
        // The declaration below creates 1 seconds instant from
        // 1970.
        Instant instant = new Instant(1000);

        // Get a new copy of instant with 500 duration added.
        instant = instant.plus(500);

        // Get a new copy of instant with 250 duration taken away.
        instant = instant.minus(250);
        System.out.println("Milliseconds = " + instant.getMillis());

        // Creating an instant that represent the current date.
        DateTime dateTime = new DateTime();
        System.out.println("Date Time = " + dateTime);

        // Creating an instant of a specific date and time.
        DateTime independenceDay = new DateTime(2017, 8, 17, 0, 0, 0);
        System.out.println("Independence Day = " + independenceDay);
    }
}

Here is the result of our program:

Milliseconds = 1250
Date Time = 2017-01-16T23:32:15.070+08:00
Independence Day = 2017-08-17T00:00:00.000+08:00

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, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply