I'm trying to write something that accepts a date in yyyymmdd format and a number that will give me the date minus that number.
For example, if I pass in 20010403 and 2, I should return 20010401.
Here's what I have so far, but am stuck:
public static String DateRoller(String strDate, int intDaysToRoll)
{
java.util.Calendar rcal = null;
rcal = GregorianCalendar.getInstance();
for(int i = 1;i<intDaysToRoll;i++)
{
rcal.roll(rcal.DATE,false); //Roll back 1 day...
}
Date curDate = rcal.getTime();
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyymmdd");
return sdf1.format(curDate);
} //End DateRoller
Currently it doesn't take the date I pass into consideration, but even the current date doesn't roll back the way it should...
roll ends up not working...It didn't roll the month or year, so was useless to me...
Here is what I ended up with:
[javacode]
public static String DateRoller(String strDate, int intDaysToRoll)
{
java.util.Date curDate;
SimpleDateFormat sdf2 = new SimpleDateFormat ("yyyyMMdd");
Date dtTemp = new Date();
try
{
dtTemp = sdf2.parse(strDate);
}
catch(ParseException e){}
int y = dtTemp.getYear()+1900;
int m = dtTemp.getMonth();
int d = dtTemp.getDate();
java.util.GregorianCalendar rcal = new GregorianCalendar(y,m,d);
curDate = rcal.getTime ( );
long msCDate = curDate.getTime(); //Transforms the current date into miliseconds
long msYDate = msCDate - (86400000*intDaysToRoll); // Subtracts off X day's worth of miliseconds
java.util.Date yestDate = new java.util.Date (msYDate); //Transforms the miliseconds into a correct date
System.out.println(strDate + " - " + intDaysToRoll + " = " + yestDate.toString());
return sdf2.format(yestDate);
} //End DateRoller[\javacode]
Bookmarks