7

I need to do the CountDown Days from one date to the second date

e.g

CURRENT_DATE:3/1/2013 NEXT_DATE:21/01/2013

then it displays ::17 DAYS LEFT

I implemented code like these

String inputDateString = "01/22/2013";
Calendar calCurr = Calendar.getInstance();
Calendar calNext = Calendar.getInstance();
calNext.setTime(new Date(inputDateString)); 

if(calNext.after(calCurr)) 
{
    long timeDiff = calNext.getTimeInMillis() - calCurr.getTimeInMillis();
    int daysLeft = (int) (timeDiff/DateUtils.DAY_IN_MILLIS);
    dni.setText("Days Left: "+daysLeft);
}
else
{
    long timeDiff = calCurr.getTimeInMillis() - calNext.getTimeInMillis();
    timeDiff = DateUtils.YEAR_IN_MILLIS - timeDiff;
    int daysLeft = (int) (timeDiff/DateUtils.DAY_IN_MILLIS);
}

Is there a better way to do achieve these?

cowls
  • 24,013
  • 8
  • 48
  • 78
Radek.Dev
  • 73
  • 1
  • 3
  • 3
    Use JodaTime, it's kind of simple stuff with such library ;-) http://stackoverflow.com/questions/8026136/find-remaining-day-and-time-using-jodatime – Marek Sebera Jan 04 '13 at 11:06
  • See this [question about countdown to Christmas](http://stackoverflow.com/q/11118262/642706), using Joda-Time. – Basil Bourque Mar 02 '14 at 11:22

6 Answers6

5

Using Calendar's Methods:

String inputDateString = "01/22/2013";
Calendar calCurr = Calendar.getInstance();
Calendar day = Calendar.getInstance();
day.setTime(new SimpleDateFormat("MM/dd/yyyy").parse(inputDateString));
if(day.after(calCurr)){
               System.out.println("Days Left: " + (day.get(Calendar.DAY_OF_MONTH) -(calCurr.get(Calendar.DAY_OF_MONTH))) );
}

Output: Days Left: 17

And to increment the year by 1 , you could use Calendar.add() method

        day.add(Calendar.YEAR, 1);
PermGenError
  • 45,977
  • 8
  • 87
  • 106
  • FYI, the troublesome old date-time classes such as `java.util.Date`, `java.util.Calendar`, and `java.text.SimpleDateFormat` are now legacy, supplanted by the [java.time](https://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes. Much of the java.time functionality is back-ported to Java 6 & Java 7 in the [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/) project. Further adapted for earlier Android in the [***ThreeTenABP***](https://github.com/JakeWharton/ThreeTenABP) project. See [*How to use ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706). – Basil Bourque Jan 28 '18 at 22:47
  • You use get(Calendar.DAY_OF_MONTH) difference between two dates. I returns wrong amount of days when the difference is more than 1 month. – Yazon2006 Jul 17 '18 at 10:48
  • Yes, this only works for days within the same month. If you try 8 (October) - 30 (September), this will return -22 which is a wrong value. – Suri Sep 30 '19 at 01:38
2

There are several libraries to convert date to n days format:

hsz
  • 148,279
  • 62
  • 259
  • 315
1

I use this class

import android.text.format.DateUtils;

import java.util.Date;

import static android.text.format.DateUtils.FORMAT_NUMERIC_DATE;
import static android.text.format.DateUtils.FORMAT_SHOW_DATE;
import static android.text.format.DateUtils.FORMAT_SHOW_YEAR;
import static android.text.format.DateUtils.MINUTE_IN_MILLIS;

/**
 * Utilities for dealing with dates and times
 */
public class TimeUtils {

    /**
     * Get relative time for date
     *
     * @param date
     * @return relative time
     */
    public static CharSequence getRelativeTime(final Date date) {
        long now = System.currentTimeMillis();
        if (Math.abs(now - date.getTime()) > 60000)
            return DateUtils.getRelativeTimeSpanString(date.getTime(), now,
                    MINUTE_IN_MILLIS, FORMAT_SHOW_DATE | FORMAT_SHOW_YEAR
                    | FORMAT_NUMERIC_DATE);
        else
            return "Just now";
    }
}

TimeUtils.getRelativeTime(date) returns text like
Just now,
2 min. ago,
2 hours ago,
2 days ago,
04.11.2013

beholderrk
  • 730
  • 8
  • 17
1

tl;dr

java.time.temporal.ChronoUnit.DAYS.between( 
    LocalDate.now() , 
    LocalDate.of( 2013 , Month.JANUARY , 21 ) 
) 

java.time

The modern approach uses the java.time classes.

LocalDate

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

Determine your dates.

LocalDate start = LocalDate.of( 2013 , Month.JANUARY , 3 ) ;  // 3/1/2013
LocalDate stop = LocalDate.of( 2013 , Month.JANUARY , 21 ) ; // 21/01/2013

Today’s date

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, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.

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 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" ) ;  // Or `ZoneId.systemDefault()` to indicate explicitly that you want the JVM’s current default time zone. Beware of that default changing *during* runtime.
LocalDate today = LocalDate.now( z ) ;

Elapsed days

The ChronoUnit enum calculates elapsed time in various granularity.

long daysElapsed = ChronoUnit.DAYS.between( start , stop ) ;

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.

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?

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

I searched this code on internet, but didn't manage to find. Though I'm replying late, this will be useful piece of code.

public static String getTimeLeft(String date) { // dateFormat = "yyyy-MM-dd"
    String[] DateSplit = date.split("-");
    int month = Integer.parseInt(DateSplit[1]) - 1, // if month is november  then subtract by 1
    year = Integer.parseInt(DateSplit[0]), day = Integer
            .parseInt(DateSplit[2]), hour = 0, minute = 0, second = 0;
    Calendar now = Calendar.getInstance();

    int sec = second - Calendar.getInstance().get(Calendar.SECOND), min = minute
            - Calendar.getInstance().get(Calendar.MINUTE), hr = hour
            - Calendar.getInstance().get(Calendar.HOUR_OF_DAY), dy = day
            - Calendar.getInstance().get(Calendar.DATE), mnth = month
            - Calendar.getInstance().get(Calendar.MONTH), daysinmnth = 32 - dy;

    Calendar end = Calendar.getInstance();

    end.set(year, month, day);

    if (mnth != 0) {
        if (dy != 0) {
            if (sec < 0) {
                sec = (sec + 60) % 60;
                min--;
            }
            if (min < 0) {
                min = (min + 60) % 60;
                hr--;
            }
            if (hr < 0) {
                hr = (hr + 24) % 24;
                dy--;
            }
            if (dy < 0) {
                dy = (dy + daysinmnth) % daysinmnth;
                mnth--;
            }
            if (mnth < 0) {
                mnth = (mnth + 12) % 12;
            }
        }
    }

    String hrtext = (hr == 1) ? "hour" : "hours", dytext = (dy == 1) ? "day"
            : "days", mnthtext = (mnth == 1) ? "month" : "months";

    if (now.after(end)) {
        return "";
    } else {
        String months = "", days = "", hours = "";
        months = (mnth > 0) ? mnth + " " + mnthtext : "";
        if (mnth <= 0) {
            days = (dy > 0) ? dy + " " + dytext : "";
            if (dy <= 0) {
                hours = (hr > 0) ? hr + " " + hrtext : "";
            }
        }
        //Log.d("DATE", months + " 1 " + days + " 2 " + hours);
        return months + days + hours;
    }
}
Nitesh morajkar
  • 391
  • 1
  • 3
  • 11
0

The other answers ignore time zone, which may be crucial depending on how accurate you want your countdown. If you do not specify a time zone, you get the JVM's default.

The java.util.Date & .Calendar classes are notoriously troublesome. Avoid them. Use either Joda-Time or the new java.time package in Java 8.

A bit of code in Joda-Time 2.3, untested (off the top of my head). Search StackOverflow for many more examples.

String input = "01/22/2013";
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTimeFormatter formatterInput = DateTimeFormat.forPattern( "MM/dd/yyyy" ).withZone( timeZone );
DateTime future = formatterInput.parseDateTime( input );

DateTime now = new DateTime( timeZone );

int days = Days.daysBetween( now, future ).getDays();
Interval interval = new Interval( now, future );
Period period = new Period( interval );

Do some System.out.println calls for those variables and be amazed.

The string format you'll see is ISO 8601. You can create other formats as well.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154