Amir
Amir

Reputation: 83

Percentage between two dates compared to today in android/java

How I can find percentage between two dates compared to today in android/java? This question is based on this question.

I want to do something like this:

    Calendar c = Calendar.getInstance();
    yeartoday = c.get(Calendar.YEAR);
    monthtoday = c.get(Calendar.MONTH);
    daytoday = c.get(Calendar.DAY_OF_MONTH);
...

    Date datestart = getDate(styear,(stmonth-1),stday);
    Date dateend = getDate(year,(month-1),day);
    Date datetoday = getDate(yeartoday,monthtoday,daytoday);
    double percent = (((datetoday - datestart) / (dateend - datestart)) * 100);
...
public Date getDate(int year,int month,int day){
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.YEAR, year);
    calendar.set(Calendar.MONTH, month);
    calendar.set(Calendar.DAY_OF_MONTH, day);
    Date date = calendar.getTime();
    return date;
}

Upvotes: 1

Views: 1274

Answers (2)

Basil Bourque
Basil Bourque

Reputation: 339472

tl;dr

( ChronoUnit.DAYS.between( start , today ) * 100 ) 
/ 
ChronoUnit.DAYS.between( start , stop )

java.time

You are using terrible date-time classes that were supplanted years ago by the java.time classes defined in JSR 310.

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone or offset-from-UTC.

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.

If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument. If critical, confirm the zone with your user.

Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" ) ;  
LocalDate today = LocalDate.now( z ) ;

If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the code becomes ambiguous to read in that we do not know for certain if you intended to use the default or if you, like so many programmers, were unaware of the issue.

ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.

Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.

LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ;  // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.

Or, better, use the Month enum objects pre-defined, one for each month of the year. Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety. Ditto for Year & YearMonth.

LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;

Elapsed days

You seem to want a percentage based on number of days. To get a count of elapsed days, use the between method on the ChronoUnit enum class.

long days = ChronoUnit.DAYS.between( earlier , later ) ;

With a pair of these integers, you can calculate your percentage.

Example

ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
LocalDate start = today.minusDays( 5 ) ;
LocalDate stop = today.plusDays( 15 ) ;

long totalDays = ChronoUnit.DAYS.between( start , stop ) ;
long elapsedDays = ChronoUnit.DAYS.between( start , today ) ;

long percentComplete = ( elapsedDays * 100 ) / totalDays ;

Dump to console.

System.out.println( "start.toString(): " + start ) ;
System.out.println( "today.toString(): " + today ) ;
System.out.println( "stop.toString(): " + stop ) ;
System.out.println( "totalDays: " + totalDays ) ;
System.out.println( "elapsedDays: " + elapsedDays ) ;
System.out.println( percentComplete + "%" ) ;

See this code run live at IdeOne.com.

start.toString(): 2019-06-04

today.toString(): 2019-06-09

stop.toString(): 2019-06-24

totalDays: 20

elapsedDays: 5

25%

Validate inputs

Of course, for real work you need to do a bit more.

You should verify that the start is before the stop.

boolean startIsBeforeStop = start.isBefore( stop ) ;

You need to verify that today is between the pair of dates.

boolean todayIsWithinRange = ( ! today.isBefore( start ) ) && today.isBefore( stop ) ;

ThreeTen-Extra

If your work often involves date ranges, add the ThreeTen-Extra library to your project. This gives you the handy LocalDateRange class.

LocalDateRange range = LocalDateRange.of( start , stop ) ;
boolean startIsBeforeStop = ( range.lengthInDays() > 0 ) ; // A negative number beens the start is *not* before the stop.
boolean todayIsWithinRange = range.contains( today ) ;

About java.time

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.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Upvotes: 5

Amir
Amir

Reputation: 83

That's what I did:

    double millisstart = datestart.getTime();
    double millisend = dateend.getTime();
    double millistoday = datetoday.getTime();
    double percent = (((millistoday - millisstart) / (millisend - millisstart)) * 100);
    percentAsString = Double.toString(percent);

    txt5.setText(percentAsString);

Upvotes: 2

Related Questions