Skip to main content Link Menu Expand (external link) Document Search Copy Copied

Using the toDate() method

Header Image

Ahoy there, matey! Today, we be talkin’ about convertin’ a JodaTime DateTime object to a Java Date object using the toDate() method. This method be handy for when ye need to work with libraries or APIs that only accept Java Date objects.

Converting a JodaTime DateTime object to a Java Date object

To convert a JodaTime DateTime object to a Java Date object, all ye need to do be call the toDate() method on the DateTime object. The toDate() method returns a Java Date object that represents the same date and time as the DateTime object.

Here be an example:

import org.joda.time.DateTime;
import java.util.Date;

public class PirateTime {
  public static void main(String[] args) {
    DateTime jodaTime = new DateTime(2023, 4, 26, 14, 30, 0);
    Date javaDate = jodaTime.toDate();
    System.out.println("JodaTime DateTime: " + jodaTime);
    System.out.println("Java Date: " + javaDate);
  }
}

In this example, we create a JodaTime DateTime object with the date and time April 26th, 2023 at 2:30 PM. We then call the toDate() method on the DateTime object and store the resulting Java Date object in the javaDate variable. We print out both the JodaTime DateTime object and the Java Date object to the console.

Conclusion

Using the toDate() method to convert a JodaTime DateTime object to a Java Date object be easy as pie! With this method, ye can easily work with libraries or APIs that only accept Java Date objects. In future articles, we’ll explore more JodaTime functionality that will make yer programming life easier. Until then, keep on sailin’ the high seas of code!