How to Get Difference Between Two Dates in Android, Tried Every Thing and Post

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

Kotlin: Getting the difference betweeen two dates (now and previous date)

I would use java.time.LocalDate for parsing and today along with a java.time.Period that calculates the period between two LocalDates for you.

See this example:

fun main(args: Array<String>) {
// parse the date with a suitable formatter
val from = LocalDate.parse("04112005", DateTimeFormatter.ofPattern("ddMMyyyy"))
// get today's date
val today = LocalDate.now()
// calculate the period between those two
var period = Period.between(from, today)
// and print it in a human-readable way
println("The difference between " + from.format(DateTimeFormatter.ISO_LOCAL_DATE)
+ " and " + today.format(DateTimeFormatter.ISO_LOCAL_DATE) + " is "
+ period.getYears() + " years, " + period.getMonths() + " months and "
+ period.getDays() + " days")
}

The output for a today of 2020-02-21 is

The difference between 2005-11-04 and 2020-02-21 is 14 years, 3 months and 17 days

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 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

Getting difference between two dates Android

The reason you get 1970 is because it is the epoch date in milli seconds. To get the actual difference use the below.

Use JodaTime

How to get difference between two dates in Days, Hours (24), Minutes (60), Seconds(60) in android

To calculate the "rest" hours like you said. (So below 24 hours) you can use modulo.

In computing, the modulo operation finds the remainder after division
of one number by another (sometimes called modulus).

int hours = theAmountOfHours % 24

In your example

Log.e("TAG_5", "Day Difference: " + days);
Log.e("TAG_5", "hours Difference: " + hours % 24);
Log.e("TAG_5", "Minute Difference: " + minutes % 60);
Log.e("TAG_5", "Seconds Difference: " + seconds % 60);

Sources: Wikipedia

I am trying to calculate difference between two dates in seconds. (Java/Android)

I think you're somehow mixing java.sql.Date and java.util.Date.

I would try simplifying the code. Something like this.

public class Test012 {

public static void main(String[] args) throws Exception {
System.out.println( seconds() );
System.out.println( seconds2() );
System.out.println( days3() );
}

public static long seconds() throws Exception {
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
java.util.Date d1 = sdf.parse("1986-04-08");
java.util.Date d2 = sdf.parse("2013-11-28");
return ( d2.getTime() - d1.getTime() ) / 1000;
}

public static long seconds2() throws Exception {
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
java.util.Date d1 = sdf.parse("1986-04-08");
java.util.Date d2 = new java.util.Date();
return ( d2.getTime() - d1.getTime() ) / 1000;
}

public static long days3() throws Exception {
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
java.util.Date d1 = sdf.parse("2008-01-01");
java.util.Date d2 = sdf.parse("2009-01-01");
return ( d2.getTime() - d1.getTime() ) / 1000 / 60 / 60 / 24;
}

}

I also tried

select datediff(ss, '4/8/1986', '11/28/2013')  --- US date format

in SQL Server and it prints the same thing as this java program,
it prints 872294400. So this seems to be the correct value.

Are you sure the dates coming on your input are the right ones
(are equal to those I hardcoded in my test program)?
I would check that too.

Also, are you sure your dates have zero time parts? That's what the link/service you posted assumes.

date difference in days, in Android

Date#compareTo(Date)

see: http://developer.android.com/reference/java/util/Date.html

or you could use http://developer.android.com/reference/java/util/Calendar.html if you need more details about the date difference, e.g http://developer.android.com/reference/java/util/GregorianCalendar.html

How to get time difference between two dates in Android App?

Using a SharedPreference to store the start time is exactly right if you have a single start time, although you probably want to store Calendar.getInstance().getTimeInMillis() instead of the object itself. You can then restore it by using

long startMillis = mSharedPreferences.getLong(START_TIME_KEY, 0L);
Calendar startTime = Calendar.getInstance();
startTime.setTimeInMillis(millis);

Computing the difference is often easier just as milliseconds:

long now = System.currentTimeMillis();
long difference = now - startMillis;

You can then output it by using DateUtils.formatElapsedTime():

long differenceInSeconds = difference / DateUtils.SECOND_IN_MILLIS;
// formatted will be HH:MM:SS or MM:SS
String formatted = DateUtils.formatElapsedTime(differenceInSeconds);

Calculating the difference between two Java date instances

The JDK Date API is horribly broken unfortunately. I recommend using Joda Time library.

Joda Time has a concept of time Interval:

Interval interval = new Interval(oldTime, new Instant());

EDIT: By the way, Joda has two concepts: Interval for representing an interval of time between two time instants (represent time between 8am and 10am), and a Duration that represents a length of time without the actual time boundaries (e.g. represent two hours!)

If you only care about time comparisions, most Date implementations (including the JDK one) implements Comparable interface which allows you to use the Comparable.compareTo()



Related Topics



Leave a reply



Submit