This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Java in General and the fly likes Subtracting from java.util.Date Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Subtracting from java.util.Date" Watch "Subtracting from java.util.Date" New topic
Author

Subtracting from java.util.Date

Gayatri Ganesh
Ranch Hand

Joined: Dec 23, 2003
Posts: 143
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

Joined: Mar 26, 2002
Posts: 262
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();


Fun programming etcetera!
Gayatri Ganesh
Ranch Hand

Joined: Dec 23, 2003
Posts: 143
Thanks Dave.
It works...
Bhaskar boddupalli
Greenhorn

Joined: Sep 07, 2012
Posts: 13
yes...
Tony Docherty
Bartender

Joined: Aug 07, 2007
Posts: 2176
    
  47
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

Joined: Sep 07, 2012
Posts: 13
Thanks.. i had found my mistake
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19656
    
  18

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Subtracting from java.util.Date
 
Similar Threads
daysOfWeek function implementation
how to use date in java
HELP - java.sql.Date
Schedule a Timer for (starting Date, No of times, no of days) problem
Schedule a Timer for (starting Date, No of times, no of days) problem