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>
Latest posts by Wayan (see all)
- How do I use Proxy class to configure HTTP and SOCKS proxies in Java? - March 27, 2025
- How do I retrieve network interface information using NetworkInterface in Java? - March 26, 2025
- How do I work with InetAddress to resolve IP addresses in Java? - March 25, 2025