sunny sunny - 2 months ago 11
Java Question

How to get starting date and end date of year in Android?

I need help in getting start and end date of current year, last year and next year.

Below is my code: this code is work fine for month, can I modify it for year?

Note: this code is only for example.

protected void getDataByMonths(int currentDayOfMonth) {

Calendar calendar = Calendar.getInstance();

int year = calendar.get(Calendar.YEAR);

int month;

if (currentDayOfMonth >= 2) {

month = calendar.get(Calendar.MONTH) + 1;
} else {

month = calendar.get(Calendar.MONTH) - currentDayOfMonth;
}
int day = 1;

calendar.set(year, month, day);

DateFormat df = new SimpleDateFormat("MM/dd/yyyy");

int numOfDaysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

String firstday = String.valueOf(df.format(calendar.getTime()));

calendar.add(Calendar.DAY_OF_MONTH, numOfDaysInMonth - 1);

String lastday = String.valueOf(df.format(calendar.getTime()));


String result = getButtonName(button) + " From :" + getDateInMonthFormat(firstday) + " " + "To :" + getDateInMonthFormat(lastday);

finalcontacts = mySqliteDBhelper.getContactsBetweenRange(button, getDateInMilliseconds(firstday), getDateInMilliseconds(lastday));

finalstatus.setText(result);
}

Answer

Check this:

public static String GetYearSlot(int option,String inputDate)
    {
        SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy",java.util.Locale.getDefault());
        Date myDate = null;
        try
        {
            myDate = sdf.parse(inputDate);
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(myDate);

        calendar.add(Calendar.YEAR, option);
        calendar.set(Calendar.DAY_OF_YEAR, 1);
        Date YearFirstDay = calendar.getTime();
        calendar.set(Calendar.MONTH, 11);
        calendar.set(Calendar.DAY_OF_MONTH, 31);
        Date YearLastDay = calendar.getTime();

        return sdf.format(YearFirstDay)+"-"+sdf.format(YearLastDay);
    }

how to use:

GetYearSlot(1, fromDate): it gives you next year from the date you passed(input 1)

GetYearSlot(0, fromDate): it gives you current year from the date you passed(input 0)

GetYearSlot(-1, fromDate): it gives you previous year from the date you passed(input -1)

Comments