Convert SQL Timestamp into Joda-Time DateTime and Vice Versa in Java

Tags: Joda Time DateTime Joda DateTime Timestamp Convert

In this Joda-Time tutorial, we learn how to convert an SQL Timestamp object into Joda-Time’ DateTime object and vice versace from Joda-Time’s DateTime into a Timestamp in Java.

Add Joda Time library to your Java project

To use Joda Time Java library in the Gradle build project, add the following dependency into the build.gradle file.

compile group: 'joda-time', name: 'joda-time', version: '2.10.9'

To use Joda Time Java library in the Maven build project, add the following dependency into the pom.xml file.

<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.10.9</version>
</dependency>

To download the Joda Time .jar file you can visit Joda Time releases page at github.com/JodaOrg/joda-time

Convert java.sql.Timestamp into org.joda.time.DateTime

TimestampToDateTime.java

import org.joda.time.DateTime;

import java.sql.Timestamp;

public class TimestampToDateTime {
    public static void main(String[] args) {
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());

        DateTime dateTime = new DateTime(timestamp);

        System.out.println("Timestamp Value: " + timestamp);
        System.out.println("DateTime Value: " + dateTime);
    }
}
The output is:
Timestamp Value: 2021-01-17 18:25:01.106
DateTime Value: 2021-01-17T18:25:01.106+07:00

Convert org.joda.time.DateTime into java.sql.Timestamp

DateTimeToTimestamp.java

import org.joda.time.DateTime;

import java.sql.Timestamp;

public class DateTimeToTimestamp {
    public static void main(String[] args) {
        DateTime dateTime = DateTime.now();

        Timestamp timestamp = new Timestamp(dateTime.getMillis());

        System.out.println("DateTime Value: " + dateTime);
        System.out.println("Timestamp Value: " + timestamp);
    }
}
The output is:
DateTime Value: 2021-01-17T18:25:09.419+07:00
Timestamp Value: 2021-01-17 18:25:09.419

Happy Coding 😊

Convert Joda-Time DateTime into Date in Java

Joda-Time Create UTC DateTime in Java

Joda Time DateTime by Examples in Java

Joda-Time Create DateTime with Time Start Of the Day in Java

Convert Joda-Time DateTime into String and Vice Versa in Java

Convert Joda-Time DateTime into Calendar and Vice Versa in Java

Format Joda-Time DateTime String using ISODateTimeFormat in Java

Compare Joda-Time DateTime using DateTimeComparator in Java

Joda-Time Create DateTime with Time End of the Day in Java

Get Date and Time fields value of Joda-Time DateTime object in Java