Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I saw all the post in here and still I can't figure how do get difference between two android dates.

This is what I do:

long diff = date1.getTime() - date2.getTime(); Date diffDate = new Date(diff); 

and I get: the date is Jan. 1, 1970 and the time is always bigger in two hours...I'm from Israel so the two hours is timeOffset.

How can I get normal difference???

like image 854
Alex Kapustian Avatar asked May 21 '12 18:05

Alex Kapustian


People also ask

How can I get the difference between two dates in Android?

This example demonstrates how do I get the difference between two dates in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

How do you find the difference between two date objects?

Calculate the no. of days between two dates, divide the time difference of both the dates by no. of milliseconds in a day (1000*60*60*24) Print the final result using document.

How do I find the difference between two dates in the same column?

To calculate the difference between two dates in the same column, we use the createdDate column of the registration table and apply the DATEDIFF function on that column. To find the difference between two dates in the same column, we need two dates from the same column.

How do you find the difference between two dates on Kotlin?

This is what I do: long diff = date1. getTime() - date2. getTime(); Date diffDate = new Date(diff);


2 Answers

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

like image 185
Dan F Avatar answered Sep 22 '22 08:09

Dan F


    long diffInMillisec = date1.getTime() - date2.getTime();      long diffInDays = TimeUnit.MILLISECONDS.toDays(diffInMillisec);     long diffInHours = TimeUnit.MILLISECONDS.toHours(diffInMillisec);     long diffInMin = TimeUnit.MILLISECONDS.toMinutes(diffInMillisec);     long diffInSec = TimeUnit.MILLISECONDS.toSeconds(diffInMillisec); 
like image 27
Dude Avatar answered Sep 26 '22 08:09

Dude