Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
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
Author

date arithmetic

Edwin Davidson
Greenhorn

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).
Edwin
Michael Dunn
Ranch Hand

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

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 !!!
Edwin
************************************************************
//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");
System.out.println(sdfdate.format(now));
System.out.println(sdftime.format(now));
//create a new date - note: months are NOT 1-12 but 0-11 (zero-indexed)
Date otherDate=new GregorianCalendar(1987,02,23).getTime();
System.out.println(sdfdate.format(otherDate));
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
System.out.println(dateFormat.format(tomorrow.getTime()));
//this imposes a Date value on a GregorianCalendar variable - interesting !
tomorrow.setTime(now);
System.out.println(dateFormat.format(tomorrow.getTime()));
}
}
 
Consider Paul's rocket mass heater.
 
subject: date arithmetic
 
Similar Threads
first date and last date of month
WA #1.....word association
SCJP validity.
Date date = new Date(String str)
Use of the clone() in getters and setters for Mutable Objects