Friday 5 November 2021

Find the difference between two joda Datetime objects

Approach 1: Using Duration object.

 

DateTimeDifference1.java

package com.sample.app.joda;

import org.joda.time.DateTime;
import org.joda.time.Duration;

public class DateTimeDifference1 {

	public static void main(String args[]) {
		DateTime today = new DateTime();
		DateTime tomorrow = today.plusDays(1);

		Duration duration = new Duration(today, tomorrow);

		System.out.println("Difference between today and tomorrow:");
		System.out.println("\tin days: " + duration.getStandardDays());
		System.out.println("\tin hours: " + duration.getStandardHours());
		System.out.println("\tin minutes: " + duration.getStandardMinutes());
		System.out.println("\tin seconds: " + duration.getStandardSeconds());
	}

}

Output

Difference between today and tomorrow:
	in days: 1
	in hours: 24
	in minutes: 1440
	in seconds: 86400


Approach 2: Using Days.daysBetween, Hours.hoursBetween, Minutes.minutesBetween and Seconds.secondsBetween methods.

 

DateTimeDifference2.java

package com.sample.app.joda;

import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.Hours;
import org.joda.time.Minutes;
import org.joda.time.Seconds;

public class DateTimeDifference2 {

	public static void main(String args[]) {
		DateTime today = new DateTime();
		DateTime tomorrow = today.plusDays(1);

		System.out.println("Difference between today and tomorrow:");
		System.out.println("\tin days: " + Days.daysBetween(today, tomorrow).getDays());
		System.out.println("\tin hours: " + Hours.hoursBetween(today, tomorrow).getHours());
		System.out.println("\tin minutes: " + Minutes.minutesBetween(today, tomorrow).getMinutes());
		System.out.println("\tin seconds: " + Seconds.secondsBetween(today, tomorrow).getSeconds());
	}

}


Output

Difference between today and tomorrow:
	in days: 1
	in hours: 24
	in minutes: 1440
	in seconds: 86400






 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment