1

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);
    }
halfer
  • 19,824
  • 17
  • 99
  • 186
sunny
  • 179
  • 2
  • 14

3 Answers3

5

Assuming that you cannot use Java 8, here is how it could be done:

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

// Create first day of year
Calendar firstDayOfCurrentYear = Calendar.getInstance();
firstDayOfCurrentYear.set(Calendar.DATE, 1);
firstDayOfCurrentYear.set(Calendar.MONTH, 0);
System.out.println(df.format(firstDayOfCurrentYear.getTime()));

// Create last day of year
Calendar lastDayOfCurrentYear = Calendar.getInstance();
lastDayOfCurrentYear.set(Calendar.DATE, 31);
lastDayOfCurrentYear.set(Calendar.MONTH, 11);
System.out.println(df.format(lastDayOfCurrentYear.getTime()));

// Create first day of next year
Calendar firstDayOfNextYear = Calendar.getInstance();
firstDayOfNextYear.add(Calendar.YEAR, 1);
firstDayOfNextYear.set(Calendar.DATE, 1);
firstDayOfNextYear.set(Calendar.MONTH, 0);
System.out.println(df.format(firstDayOfNextYear.getTime()));

// Create last day of next year
Calendar lastDayOfNextYear = Calendar.getInstance();
lastDayOfNextYear.add(Calendar.YEAR, 1);
lastDayOfNextYear.set(Calendar.DATE, 31);
lastDayOfNextYear.set(Calendar.MONTH, 11);
System.out.println(df.format(lastDayOfNextYear.getTime()));

Output:

01/01/2016
12/31/2016
01/01/2017
12/31/2017
Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
2

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)

Manish Jain
  • 2,139
  • 19
  • 15
1

java.time

You are using troublesome old legacy date-time classes now supplanted by the java.time classes.

First get the current date.

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

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.

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

Use Year to represent the entire year as an object.

Year thisYear = Year.from( today );
Year nextYear = thisYear.plusYears( 1 );
Year lastYear = thisYear.minusYears( 1 );

Usually in date-time work we represent a span of time using the Half-Open approach. In this approach the beginning is inclusive while the ending is exclusive. So a year would start on January first and run up to, but not include, January 1 of the following year.

If on Java 8, you could include the ThreeTen-Extra project and its Interval class to represent the span of time.

Otherwise do it yourself.

LocalDate thisYearStart = thisYear.atDay( 1 );
LocalDate lastYearStart = lastYear.atDay( 1 );
LocalDate nextYearStart = nextYear.atDay( 1 );

If you truly need the last day of the year, you could just subtract one day from the first day of the following year. Even easier is using a TemporalAdjuster defined in TemporalAdjusters class.

LocalDate thisYearFirstDay = today.with( TemporalAdjusters.firstDayOfYear() );
LocalDate thisYearLastDay = today.with( TemporalAdjusters.lastDayOfYear() );

LocalDate nextYearFirstDay = thisYearLastDay.plusDays( 1 );
LocalDate nextYearLastDay = nextYearFirstDay.with( TemporalAdjusters.lastDayOfYear() );

LocalDate lastYearLastDay = thisYearFirstDay.minusDays( 1 );
LocalDate lastYearFirstDay = lastYearLastDay.with( TemporalAdjusters.firstDayOfYear() );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.

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

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

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

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