The difference between two dates in days varies

Date d = new Date(today.getTimeInMillis());
Date d1 = new Date(dueDate.getTimeInMillis());

int daysUntil = (int) ((d1.getTime() - d.getTime())/ (1000 * 60 * 60 * 24));

Using the code above, where todayis the calendar set at 00:00 on the current day, and dueDateset at 00:00 on the day when I compare today, my results are different from this.

There is something about this that changes, making my conclusion either x or x + 1, where x is the correct answer.

What is the problem, and what can I do to make it more stable?

0
source share
2 answers

Unclear question

You do not provide actual values, so we cannot pinpoint the problem. We do not know what the variables todayand represent dueDate.

, , java.util.Date/.Calendar, java.time. . Tutorial. JSR 310, Joda-Time ThreeTen-Extra.

java.time:

  • An Instant - UTC.
  • A ZoneId . , 3-4 , "EST" "IST", .
  • , ZonedDateTime= + ZoneId.

ThreeTen-Extra

, java.time , . ThreeTen-Extra Days class between, . ThreeTen-Extra , java.time JSR.

ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime now = ZonedDateTime.now ( zoneId );
ZonedDateTime then = now.minusDays ( 4 );
ZonedDateTime due = now.plusDays ( 3 );
Integer days = org.threeten.extra.Days.between ( then , due ).getAmount ();

.

System.out.println ( "From then: " + then + " to due: " + due + " = days: " + days );

: 2015-10-31T16: 01:13.082-04: 00 [/] : 2015-11-07T16: 01:13.082-05: 00 [/] = : 7

Joda

Android Java Joda-Time.

Days , Daylight (DST).

, java.util.Date Joda-Time DateTime .

// Specify a time zone rather than rely on default.
DateTimeZone timeZone = DateTimeZone.forID( "America/Regina" ); // Or "Europe/London".

DateTime now = new DateTime( timeZone );
DateTime startOfToday = now.withTimeAtStartOfDay();

DateTime fewDaysFromNow = now.plusDays( 3 );
DateTime startOfAnotherDay = fewDaysFromNow.withTimeAtStartOfDay();

Days days = Days.daysBetween( startOfToday, startOfAnotherDay );

...

System.out.println( days.getDays() + " days between " + startOfToday + " and " + startOfAnotherDay + "." );

...

3 days between 2014-01-21T00:00:00.000-06:00 and 2014-01-24T00:00:00.000-06:00.
+1

, :

  • ( )

.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d1 = sdf.parse("2016-03-20");
Date d2 = sdf.parse("2016-03-28");
int daysUntil = (int) ((d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
System.out.println(daysUntil); // 7 (should be 8)

"/". - , 2016-03-27 2 , . 23 , 24 , , .

?

, 1000 dueDate, , . , , , , . java.util.Date, .

, ( Android ), - java.util.GregorianCalendar , , , . , .

. Android, .

+1

Source: https://habr.com/ru/post/1614503/


All Articles