File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Subtracting from java.util.Date

 
Gayatri Ganesh
Ranch Hand
Posts: 143
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am looking for date functions which will allow me to subract 1 day, 1 week, 1 month, 3 mths, 1 year.

Date now = new Date();
From now, I want to subtract 1 day, 1 week, 1 month, 3 mths, 1 year.


I searched the the java.util classes.
java.uil.Calendar has a add() method but it doesn't return a java.util.Date object.

Can anyone tell me how i could do this subtraction and the return value is a java.util.Date object.

Thanks,
Gayatri
 
Dave Wingate
Ranch Hand
Posts: 262
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's been a while ... but I think you want something along the lines of:

Date startingDate;
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(startingDate);
gc.add(Calendar.DAY_OF_YEAR, -1);
Date result = gc.getTime();
 
Gayatri Ganesh
Ranch Hand
Posts: 143
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Dave.
It works...
 
Bhaskar boddupalli
Greenhorn
Posts: 13
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes...
 
Tony Docherty
Bartender
Pie
Posts: 2878
59
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if i want to subtract 21years ..

please don't say gc.add(Calendar.DAY_OF_YEAR, -21); which is not working :P

Well it wouldn't work, that is subtracting 21 days and not 21 years. If you want to subtract years you need to use:
 
Bhaskar boddupalli
Greenhorn
Posts: 13
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks.. i had found my mistake
 
Rob Spoor
Sheriff
Pie
Posts: 20372
44
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please don't edit your posts after they have been replied to. It makes the replies look odd. If Tony hadn't quoted your post I wouldn't have understood what he was going on about.
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic