• Post Reply Bookmark Topic Watch Topic
  • New Topic

Subtracting/Adding dates  RSS feed

 
Claudia Vaz
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello
I need to add and subtract dates in Java.
How can i do it?
Thanks in advance
Claudia Vaz
 
Wayne L Johnson
Ranch Hand
Posts: 399
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You probably want to avoid doing any manipulation of Date instances, and use Calendar instead. You can use the "setTime(Date date)" and "getTime()" methods of Calendar to move between Calendar and Date. And with the Calendar object you have the "add(int field, int amount)" method that allows you to add or subtract year, month, day, hour, minute, second, etc.
Calendar today = Calendar.getInstance(); // Today's date/time
today.add(Calendar.MONTH, 3); // Go three months into the future
today.add(Calendar.YEAR, -3); // Go three years into the past
...
If you play around with this for a bit you should quickly get the hang of it.
I assume this is what you mean when you say "add and subtract dates".
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!