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
<!-- https://search.maven.org/remotecontent?filepath=joda-time/joda-time/2.11.2/joda-time-2.11.2.jar -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.11.2</version>
</dependency>
Latest posts by Wayan (see all)
- How do I build simple search page using ZK and Spring Boot? - March 8, 2023
- How do I calculate days between two dates excluding weekends and holidays? - January 12, 2023
- How do I discover the quarter of a given date? - January 11, 2023