File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes date arithmetic Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "date arithmetic" Watch "date arithmetic" New topic

date arithmetic

Edwin Davidson

Joined: Nov 26, 2003
Posts: 27
I have 2 Date variables and wish to know the difference (in days) between them. Does anyone have some code for that please ?
Thank you (again).
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
Here's something from a couple of days ago
JavaRanch link
Edwin Davidson

Joined: Nov 26, 2003
Posts: 27
by browsing around I came up with a solution to my date arithmetic problem and also learned a bunch of date stuff in the process. NOW I feel better ! My code is below - shows how to do date arithmetic and formatting which is pretty cool. Thanks to all who helped.
And Java Ranch rocks !!!
//import these 5 classes first to get their functions
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.util.Calendar;
import java.util.Date;
class datetext
public static void main(String x[])
Date now=new Date();
SimpleDateFormat sdfdate=new SimpleDateFormat("MMMMMMMMM d, yyyy");
SimpleDateFormat sdftime=new SimpleDateFormat("h:m a");
//create a new date - note: months are NOT 1-12 but 0-11 (zero-indexed)
Date otherDate=new GregorianCalendar(1987,02,23).getTime();
long diff=now.getTime()-otherDate.getTime();
System.out.println(diff / 86400000L);
//84600000 is the amount of milliseconds in one day 1000L*60L*60L*24L
//how to use DateFormat
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL);
GregorianCalendar tomorrow=new GregorianCalendar();
//add 1 to the date of tomorrow
tomorrow.add(GregorianCalendar.DAY_OF_YEAR, + 1);
//display it using dateformat
//this imposes a Date value on a GregorianCalendar variable - interesting !
I agree. Here's the link:
subject: date arithmetic
jQuery in Action, 3rd edition