简体   繁体   中英

How to get previous and next day's dates in android?

I created a layout with three Buttons . My idea is to use these three buttons as a datepicker. Those three buttons are - , Today , + . If I press the today button displays today's date. When I press - it displays yesterdays date. If I press + it displays tomorrow's date. No problem. But it only works once. My requirement is to as long as I press - it has to display previous day's dates ie 19-Aug-2015 , 18-Aug-2015 , 17-Aug-2015 ,etc., My code is

 imgtoday.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            googleMap.clear();
            Date date1=new Date(System.currentTimeMillis());
            SimpleDateFormat sdf=new SimpleDateFormat("dd-MMM-yyyy");
            String date=sdf.format(date1);
            drawRoute(date);
            imgHistory.setClickable(false);
            imgHistory.setBackgroundResource(R.drawable.btn_disabled);
            calculateDistance(date);
        }
    });

    previousDay=(Button)findViewById(R.id.button9);
    nextDay=(Button)findViewById(R.id.button11);

    previousDay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            googleMap.clear();
            Date date1=new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24));
            SimpleDateFormat sdf=new SimpleDateFormat("dd-MMM-yyyy");
            String date=sdf.format(date1);
            drawRoute(date);
            calculateDistance(date);
        }
    });

    nextDay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            googleMap.clear();
            Date date1=new Date(System.currentTimeMillis() + (1000 * 60 * 60 * 24));
            SimpleDateFormat sdf=new SimpleDateFormat("dd-MMM-yyyy");
            String date=sdf.format(date1);
            drawRoute(date);
            calculateDistance(date);
        }
    });

Anyone please help. Thanks.

Use Calendar:

Calendar cal = Calendar.getInstance(); 
cal.setTime(TODAY); 
cal.add(Calendar.DAY_OF_MONTH, 1); //Adds a day
cal.add(Calendar.DAY_OF_MONTH, -1); //Goes to previous day
yourDate = cal.getTime();

Here is my code I have used for increment and decrement dates

/**
 * Get next date from current selected date
 *
 * @param date date
 */
public Date incrementDateByOne(Date date) {
    Calendar c = Calendar.getInstance();
    c.setTime(date);
    c.add(Calendar.DATE, 1);
    Date nextDate = c.getTime();
    return nextDate;
}

/**
 * Get previous date from current selected date
 *
 * @param date date
 */
public Date decrementDateByOne(Date date) {
    Calendar c = Calendar.getInstance();
    c.setTime(date);
    c.add(Calendar.DATE, -1);
    Date previousDate = c.getTime();
    return previousDate;
}

I hope it helps!

You can Use Joda-Time library to Get Easily Next and Previous Days.

https://github.com/JodaOrg/joda-time

https://github.com/dlew/joda-time-android

Example

LocalDate dateTime =  LocalDate.now()  // Here 'date' is the current date
dateTime = dateTime.plusDays(1); // get the next day date

You can find more built in functions like dateTime.plusYear(1) etc.

For your code

 previousDay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            googleMap.clear();
            LocalDate startDate = LocalDate.now() ;
            startDate = startDate.plusDays(-1); 
            DateTimeFormatter fmt1 = DateTimeFormat.forPattern("You Format here");
            String DateInstrg = date.toString(fmt1);
            // rest of you code
        }
    });

    nextDay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            googleMap.clear();
             LocalDate startDate = LocalDate.now() 
            startDate = startDate.plusDays(1); 
            DateTimeFormatter fmt1 = DateTimeFormat.forPattern("You Format here");
            String DateInstrg = date.toString(fmt1);
            // rest of you code
        }
    });

Get Previous date by following Method:

public static boolean isPreviousday(Date currenTimeZone) {
    boolean previousdate = false;
    Calendar c1 = Calendar.getInstance(); // today
    c1.add(Calendar.DAY_OF_YEAR, -1); // yesterday

    Calendar c2 = Calendar.getInstance();
    c2.setTime(currenTimeZone);
    if (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR)
            && c1.get(Calendar.DAY_OF_YEAR) == c2.get(Calendar.DAY_OF_YEAR)) {
        return previousdate = true;
    } else {
        return previousdate = false;
    }
}

Get Next Days Date by following Method

public void Date NextDay(Date date)
{
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.add(Calendar.DATE, days); //minus number would decrement the days
    return cal.getTime();
}

Crate date1 global private field and initalize in onCreate : date1=new Date(System.currentTimeMillis());

OnClick methods eg: date1=new Date(date1.getTime() +- (1000 * 60 * 60 * 24));

 c = Calendar.getInstance();
        System.out.println("Current time => " + c.getTime());
        df = new SimpleDateFormat("dd-MMM-yyyy");
        formattedDate = df.format(c.getTime());
        String str1 = this.days[c.get(Calendar.DAY_OF_WEEK)-1];
        textView.setText(formattedDate);
    next.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            c.add(Calendar.DATE, 1);
           // c.add(Calendar.DAY_OF_WEEK,1);
            formattedDate = df.format(c.getTime());

            Log.v("NEXT DATE : ", formattedDate);
            textView.setText(formattedDate);

        }
    });
    previous.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            c.add(Calendar.DATE, -1);
          //  c.add(Calendar.DAY_OF_WEEK,-1);
            formattedDate = df.format(c.getTime());

            Log.v("PREVIOUS DATE : ", formattedDate);
            textView.setText(formattedDate);
        }
    });

Here is how can you can get the number of hours later time from current time in Kotlin:

    val cal = Calendar.getInstance()     // creates calendar
    cal.time = Date()                  // sets calendar time/date
    cal.add(Calendar.HOUR_OF_DAY, 16)       // adds 16 hour
    cal.time

    //Parse the date
    val currentDate: String = SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(cal.time)

    //Parse the time
    val currentTime: String = SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(cal.time)

using calendar :

Calendar calendar = Calendar.getInstance(); 
cal.setTime(TODAY); 
cal.add(Calendar.DAY_OF_MONTH, 1); //Next day
cal.add(Calendar.DAY_OF_MONTH, -1); //Previous day
yourDate = cal.getTime();

Modify your existing code like:

int plusButtonPressed = 1;
int minusButtonPressed = 1;

previousDay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            googleMap.clear();
            Date date1=new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24) * minusButtonPressed);
            SimpleDateFormat sdf=new SimpleDateFormat("dd-MMM-yyyy");
            String date=sdf.format(date1);
            drawRoute(date);
            calculateDistance(date);
            minusButtonPressed += 1;
        }
    });

    nextDay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            googleMap.clear();
            Date date1=new Date(System.currentTimeMillis() + (1000 * 60 * 60 * 24) * plusButtonPressed);
            SimpleDateFormat sdf=new SimpleDateFormat("dd-MMM-yyyy");
            String date=sdf.format(date1);
            drawRoute(date);
            calculateDistance(date);
            plusButtonPressed += 1;
        }
    });

You don't need libraries, you can do with Calendar instance. http://developer.android.com/reference/java/util/Calendar.html there is a long explanation, but here is an extract:

Usage model. To motivate the behavior of add() and roll(), consider a user interface component with increment and decrement buttons for the month, day, and year, and an underlying GregorianCalendar. If the interface reads January 31, 1999 and the user presses the month increment button, what should it read? If the underlying implementation uses set(), it might read March 3, 1999. A better result would be February 28, 1999. Furthermore, if the user presses the month increment button again, it should read March 31, 1999, not March 28, 1999. By saving the original date and using either add() or roll(), depending on whether larger fields should be affected, the user interface can behave as most users will intuitively expect.

Note: You should always use roll and add rather than attempting to perform arithmetic operations directly on the fields of a Calendar. It is quite possible for Calendar subclasses to have fields with non-linear behavior, for example missing months or days during non-leap years. The subclasses' add and roll methods will take this into account, while simple arithmetic manipulations may give invalid results.

So you can do something like:

final SimpleDateFormat sdf=new SimpleDateFormat("dd-MMM-yyyy");
Calendar actualDate = Calendar.getInstance();
imgtoday.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            googleMap.clear();
            actualDate=Calendar.getInstance();
            String date=sdf.format(actualDate.getTime());
            drawRoute(date);
            imgHistory.setClickable(false);
            imgHistory.setBackgroundResource(R.drawable.btn_disabled);
            calculateDistance(date);
        }
    });
previousDay=(Button)findViewById(R.id.button9);
nextDay=(Button)findViewById(R.id.button11);

previousDay.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        googleMap.clear();
//modify actual date, removing one day
        actualDate.add(Calendar.DAY_OF_MONTH,-1);
        String date=sdf.format(actualDate.getTime());
        drawRoute(date);
        calculateDistance(date);
    }
});

nextDay.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        googleMap.clear();
        actualDate.add(Calendar.DAY_OF_MONTH,1);
        String date=sdf.format(actualDate.getTime());
        drawRoute(date);
        calculateDistance(date);
    }
});

PS: Don't need to reinitialize the same date format every time, just to it once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM