i have to find day difference between two date in android, i find the difference in days using timemilliseconds() but is there any other way to find difference?
tha
ChronoUnit.DAYS.between( // Total count of days.
LocalDate.of( 2018 , Month.JANUARY , 23 ) , // Represent a certain date.
LocalDate.now( ZoneId.of( "America/Montreal" ) ) // Determine today’s current date for a particular region (time zone).
)
The old Date
class is now outmoded by the java.time classes. And tracking date-time as a count-of-milliseconds-since-epoch is frustrating and error-prone.
Convert your Date
objects to Instant
. If using later versions of Android, look for new methods added to the old classes. For earlier Android, use the ThreeTen-Backport and ThreeTenABP projects’ utility class for conversion.
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Because the Instant
is always in UTC, you need to adjust into a time zone. A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
Specify a proper time zone name in the format of continent/region
, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland
. Never use the 3-4 letter pseudo-zones such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
Apply to your Instant
to get a ZonedDateTime
.
ZonedDateTime zdt = instant.atZone( z ) ;
If you care only about entire days as defined by dates, extract LocalDate
object.
LocalDate localDate = zdt.toLocalDate() ;
Get your other date, such as today.
LocalDate today = LocalDate.now( z ) ;
Count the total number of elapsed days using ChronoUnit
enum.
long days = ChronoUnit.DAYS.between( localDate , today ) ;
If instead you want a count of years and months and days, use the Period
class.
Period p = Period.between( localDate , today ) ;
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
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