-
August 28th, 2001, 10:33 AM
#1
Date minus X days
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...
Any suggestions?
Thanks!!
-
August 28th, 2001, 11:28 AM
#2
Re: Date minus X days
Try setting the time before you start rolling.
So: Calendar.getInstance() (don't use Gregorian directly)
and then rcal.setTime(date)
date will come from strDate:
So:
SimpleDateFormat sdf = new SimpleDataFormat("yyyyMMdd"); // this correct? yyyyMMdd? mm is minutes
Date date = sdf.parse(strDate);
Bayard
bayard@generationjava.com
http://www.generationjava.com
Brainbench MVP for Java
http://www.brainbench.com
-
August 28th, 2001, 12:19 PM
#3
Re: Date minus X days
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]
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|