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???
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.
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.
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.
This is what I do: long diff = date1. getTime() - date2. getTime(); Date diffDate = new Date(diff);
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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With