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

后端 未结 11 2291
天命终不由人
天命终不由人 2020-11-28 09:06

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


        
11条回答
  •  感动是毒
    2020-11-28 09:37

    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

提交回复
热议问题