Android Difference Between Two Dates

Android difference between Two Dates

DateTimeUtils obj = new DateTimeUtils();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/M/yyyy hh:mm:ss");

try {
Date date1 = simpleDateFormat.parse("10/10/2013 11:30:10");
Date date2 = simpleDateFormat.parse("13/10/2013 20:35:55");

obj.printDifference(date1, date2);

} catch (ParseException e) {
e.printStackTrace();
}

//1 minute = 60 seconds
//1 hour = 60 x 60 = 3600
//1 day = 3600 x 24 = 86400
public void printDifference(Date startDate, Date endDate) {
//milliseconds
long different = endDate.getTime() - startDate.getTime();

System.out.println("startDate : " + startDate);
System.out.println("endDate : "+ endDate);
System.out.println("different : " + different);

long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;

long elapsedDays = different / daysInMilli;
different = different % daysInMilli;

long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;

long elapsedMinutes = different / minutesInMilli;
different = different % minutesInMilli;

long elapsedSeconds = different / secondsInMilli;

System.out.printf(
"%d days, %d hours, %d minutes, %d seconds%n",
elapsedDays, elapsedHours, elapsedMinutes, elapsedSeconds);
}

out put is :

startDate : Thu Oct 10 11:30:10 SGT 2013
endDate : Sun Oct 13 20:35:55 SGT 2013
different : 291945000
3 days, 9 hours, 5 minutes, 45 seconds

Android calculate days between two dates

Your code for generating date object:

Date date = new Date("2/3/2017"); //deprecated

You are getting 28 days as answer because according to Date(String) constructor it is thinking day = 3,month = 2 and year = 2017

You can convert String to Date as follows:

String dateStr = "2/3/2017";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date = sdf.parse(dateStr);

Use above template to make your Date object. Then use below code for calculating days in between two dates. Hope this clear the thing.

It can de done as follows:

long diff = endDateValue.getTime() - startDateValue.getTime();
System.out.println ("Days: " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));

Please check link

If you use Joda Time it is much more simple:

int days = Days.daysBetween(date1, date2).getDays();

Please check JodaTime

How to use JodaTime in Java Project

How do I get difference between two dates in android?, tried every thing and post

You're close to the right answer, you are getting the difference in milliseconds between those two dates, but when you attempt to construct a date out of that difference, it is assuming you want to create a new Date object with that difference value as its epoch time. If you're looking for a time in hours, then you would simply need to do some basic arithmetic on that diff to get the different time parts.

Java:

long diff = date1.getTime() - date2.getTime();
long seconds = diff / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
long days = hours / 24;

Kotlin:

val diff: Long = date1.getTime() - date2.getTime()
val seconds = diff / 1000
val minutes = seconds / 60
val hours = minutes / 60
val days = hours / 24

All of this math will simply do integer arithmetic, so it will truncate any decimal points

Difference between two dates (Android)

You need to get the basic concepts right. When you take a difference between two Date object, you get the duration between two points in time, trying to view the difference as another time point makes no sense.

Here's a example using the Java 8 time API to get the difference between two points in time (java.time.Instant):

import java.time.Duration;
import java.time.Instant;

public class TimeDifferenceSample {

static Duration diff(Instant start, Instant end) {
return Duration.between(start, end);
}

public static void main(String [] args) {
long start = 1470712122173L;
long end = 1470712127320L;

Duration dur = diff(Instant.ofEpochMilli(start), Instant.ofEpochMilli(end));
System.out.println(dur.getSeconds() + " seconds");
}
}

Output:

5 seconds

For Android, I am not an expert, but you can check The Joda Time Project, which provides similar functions. I also found an Android verion here.

Android difference between two dates in seconds

You can turn a date object into a long (milliseconds since Jan 1, 1970), and then use TimeUnit to get the number of seconds:

long diffInMs = endDate.getTime() - startDate.getTime();

long diffInSec = TimeUnit.MILLISECONDS.toSeconds(diffInMs);

Edit:
-Corrected the name of the variable diffInMs which was written diffInM(i)s in the second line.

android diff days between two dates

Try this

public static long printDifference(Date startDate, Date endDate){

//milliseconds
long different = endDate.getTime() - startDate.getTime();

long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;

long elapsedDays = different / daysInMilli;
different = different % daysInMilli;

long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;

long elapsedMinutes = different / minutesInMilli;
different = different % minutesInMilli;

long elapsedSeconds = different / secondsInMilli;

return elapsedDays;
}

Android difference between two dates?

Calendar thatDay = Calendar.getInstance();
thatDay.set(Calendar.DAY_OF_MONTH,25);
thatDay.set(Calendar.MONTH,7); // 0-11 so 1 less
thatDay.set(Calendar.YEAR, 1985);

Calendar today = Calendar.getInstance();

long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis

long days = diff / (24 * 60 * 60 * 1000);

To Parse the date from a string, you could use

String strThatDay = "1985/08/25";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
Date d = null;
try {
d = formatter.parse(strThatDay);//catch exception
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


Calendar thatDay = Calendar.getInstance();
thatDay.setTime(d); //rest is the same....

Calculate Years and Months between Two Dates in Android

java.time

You can do it as follows:

import java.time.OffsetDateTime;
import java.time.Period;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

public class Main {
public static void main(String[] args) {
// Define format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss O yyyy");

// Date/time strings
String strEndDate = "Mon Jun 08 19:45:08 GMT+07:00 2020";
String strStartDate = "Sun Jan 22 19:45:08 GMT+07:00 2017";

// Define ZoneOffset
ZoneOffset zoneOffset = ZoneOffset.ofHours(6);

// Parse date/time strings into OffsetDateTime
OffsetDateTime startDate = OffsetDateTime.parse(strStartDate, formatter).withOffsetSameLocal(zoneOffset);
OffsetDateTime endDate = OffsetDateTime.parse(strEndDate, formatter).withOffsetSameLocal(zoneOffset);

// Calculate period between `startDate` and `endDate`
Period period = Period.between(startDate.toLocalDate(), endDate.toLocalDate());

// Display result
System.out.println(
period.getYears() + " years and " + period.getMonths() + " months since " + startDate.getYear());
}
}

Output:

3 years and 4 months since 2017

Note: Instead of using the outdated java.util.Date and SimpleDateFormat, use the modern date/time API. Check this to learn more about it.


Note: The following content has been copied from How to get start time and end time of a day in another timezone in Android

Question: Doesn’t java.time require Android API level 26?

java.time works nicely on both older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

But don't we have any other option apart from switching to ThreeTenBP
Library?

If you insisted, I suppose that a way through using Calendar, Date and SimpleDateFormat could be found. Those classes are poorly designed and long outdated, so with what I know and don’t know I would prefer ThreeTenABP.

Links

  • Oracle tutorial: Date Time explaining how to use java.time.
  • Java Specification Request (JSR) 310, where java.time was first described.
  • ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
  • ThreeTenABP, Android edition of ThreeTen Backport
  • Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
  • Wikipedia article: ISO 8601



Related Topics



Leave a reply



Submit