i try to get a previous date of custom date that selected by a user but i cant find a way to do that this is the code
calendar.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
@Override
public void onSelectedDayChange( @NonNull CalendarView view, int year, int month, int dayOfMonth ) {
finalDate = (dayOfMonth + 7) + "/" + (month - 3) + "/" + year;
try {
Date date = new SimpleDateFormat("dd/MM/yyyy").parse(finalDate);
} catch (ParseException e) {
e.printStackTrace();
}
}
});
so if i select 30/2/2020 the result is: (37/-1/2020)
Consider using java.time, the modern Java date and time API, for your date work. Not least when you need to math on dates. I frankly find it much better suited than the old and outdated Calendar
class, not to mention Date
and SimpleDateFormat
.
int year = 2020;
int month = Calendar.MARCH; // For demonstration only, don’t use Calendar in your code
int dayOfMonth = 30;
LocalDate selectedDate = LocalDate.of(year, month + 1, dayOfMonth);
LocalDate finalDate = selectedDate.minusMonths(3).plusDays(7);
System.out.println(finalDate);
Output:
2020-01-06
I believe that your Android date picker numbers months from 0 for January through 11 for December, so we need to add 1 to convert to the natural way that humans and LocalDate
number months. When we start out from 30th March, we subtract 3 months and get 30th December, then add 7 days and get 6th January. We might also have done the math in the opposite order:
LocalDate finalDate = selectedDate.plusDays(7).minusMonths(3);
In this case it gave the same result, but since months have unequal lengths, it won't always.
Isn't it because you are adding 7 to your day count and subtracting 3 from your month count? Try removing that and it should work better.
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.