Calculating Current Year in 'yyyy MM dd' format sets the incorrect value in Java

Im using the following code to calculate the current year value in yyyy-MM-dd format however the below code assigns paramStartDate value as 0001-01-01 which is incorrect It should be '2014-01-01'

else if(scopeSelected != null && scopeSelected.equalsIgnoreCase("Year To Date")){

                    Calendar calendarStart = Calendar.getInstance();
                    calendarStart.set(Calendar.YEAR,calendarStart.YEAR);
                    calendarStart.set(Calendar.MONTH,0);
                    calendarStart.set(Calendar.DAY_OF_MONTH,1);
                    Date startDate=calendarStart.getTime();
                    DateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
                    paramStartDate = dateFormat1.format(startDate);
                    setParamStartDate(paramStartDate);
                }   
Jon Skeet
people
quotationmark

This is the problem:

calendarStart.set(Calendar.YEAR,calendarStart.YEAR);

You're setting the value to Calendar.YEAR which is a constant with value 1.

If you don't want to change the year number, just remove this line completely.

(As an aside, I'd strongly recommend using Joda Time instead of the built-in Java API. Joda Time is much cleaner.)

EDIT: For the new requirement of adding a year, you'd use

calendarStart.add(Calendar.YEAR, 1);

people

See more on this question at Stackoverflow