• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
  • Piet Souris
  • Frits Walraven
  • Carey Brown

Subtracting/Adding dates

Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I need to add and subtract dates in Java.
How can i do it?
Thanks in advance
Claudia Vaz
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".
And when my army is complete, I will rule the world! But, for now, I'm going to be happy with this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
    Bookmark Topic Watch Topic
  • New Topic