Reputation: 1786
I want to get the current date and the date exactly one month previous. For example if today is 1/13/2014, I want to get today's date, 1/13/2014 and the day one month ago, 12/13/2013. For some reason, I am only getting the older date and not today's date.
Do you know why that might be?
Main code
//define Report Start and End Dates
if(startYear == 0)
{
// Get due date
Calendar curDate = Calendar.getInstance();
Calendar defaultStart = curDate;
defaultStart.set(curDate.get(Calendar.YEAR), curDate.get(Calendar.MONTH)-1, curDate.get(Calendar.DAY_OF_MONTH));
String curYear = ((Integer)curDate.get(Calendar.YEAR)).toString();
String curMonth = ((Integer)(curDate.get(Calendar.MONTH)+1)).toString();
String curDay = ((Integer)curDate.get(Calendar.DAY_OF_MONTH)).toString();
if(curDate.get(Calendar.MONTH)+1 < 10)
curMonth = "0"+((Integer)(curDate.get(Calendar.MONTH)+1)).toString();
String defaultYear = ((Integer)defaultStart.get(Calendar.YEAR)).toString();
String defaultMonth = ((Integer)(defaultStart.get(Calendar.MONTH)+1)).toString();
String defaultDay = ((Integer)defaultStart.get(Calendar.DAY_OF_MONTH)).toString();
if(defaultStart.get(Calendar.MONTH)+1 < 10)
defaultMonth = "0"+((Integer)(defaultStart.get(Calendar.MONTH)+1)).toString();
reportEndDate = curYear+"-"+curMonth+"-"+curDay;
reportStartDate = defaultYear+"-"+defaultMonth+"-"+defaultDay;
}
else
{
reportStartDate = startMonth+"/"+startYear;
reportEndDate = endMonth+"/"+endYear;
}
TextView startDateText = (TextView)findViewById(R.id.startDateText);
startDateText.setText(reportStartDate);
TextView endDateText = (TextView)findViewById(R.id.endDateText);
endDateText.setText(reportEndDate);
xml layout file
<TextView android:id="@+id/startDateText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="@color/mediumDarkGray"
android:text="XXXX-XX-XX"
/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="@color/mediumDarkGray"
android:text=" to " />
<TextView android:id="@+id/endDateText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="@color/mediumDarkGray"
android:text="XXXX-XX-XX"
/>
Upvotes: 1
Views: 139
Reputation: 44844
Rather than all this messing around why not use the built in add(Calendar.DAY_OF_MONTH, -1)
Also you could use the SimpleDateFormat
to format your Dates.
Upvotes: 0
Reputation: 10288
You set the calendar 1 month back, but then added 1 to both the start month and the end month (curMonth and defaultMonth)
This happened because you are using the same instance of Calendar for both curDate and defaultStart. You need:
Calendar defaultStart = Calendar.getInstance();
and you are fine.
Upvotes: 2