Programming Tutorials Browser Tutorials Articles Struts Tutorials Hibernate Tutorials

  Tutorial: Working in Java time

Working in Java time

Tutorial Details:

Working in Java time
Working in Java time
By: By Robert Nielsen
Learn the basics of calculating elapsed time in Java
his article builds on the information presented in my Calculating Java Dates article ( JavaWorld, December 29, 2000). Here I've listed some key points from that article that should be familiar to you. If these points are not clear to you, I recommend that you read "Calculating Java Dates" for further explanation.
Java reckons time in milliseconds before or after the start of January 1, 1970.
The Date class's constructor Date() returns an object that represents the moment the object was created. Date 's getTime() method returns a long value whose number equals the number of milliseconds before or after January 1, 1970.
The DateFormat class is used to convert Date s to String s, and vice versa. The static getDateInstance() method returns a DateFormat object in the default format; the getDateInstance(DateFormat.FIELD) returns a DateFormat object with a specified format. The format(Date d) method returns a String that represents the date, such as "January 1, 2002." Conversely, the parse(String s) method returns a Date object based on the date the String argument represents.
The appearance of String s returned by the format() method can vary according to the regional settings on the computer where the program is being run.
The GregorianCalendar class has two important constructors: GregorianCalendar() , which returns an object that represents the moment it was created, and the GregorianCalendar(int year, int month, int date) constructor used to create an object that represents an arbitrary date. The GregorianCalendar class's getTime() method returns a Date object. The add(int field, int amount) method calculates dates by adding or subtracting units of time like days, months, or years.
GregorianCalendar and time
Two GregorianCalendar class constructors can be used to deal with time. The first creates an object that represents a date, hour, and minute:
GregorianCalendar(int year, int month, int date, int hour, int minute)
The second creates an object that represents a date, hour, minute, and second:
GregorianCalendar(int year, int month, int date, int hour, int minute, int second)
First, I should note that each constructor requires date information (year, month, and day) in addition to time information. If you want to talk about 2:30 p.m., you must specify the date.
Also, each GregorianCalendar constructor creates an object that represents a moment in time calculated to the nearest millisecond. Thus, if your constructor takes arguments for only the year, month, and date, then the values for hours, minutes, seconds, and milliseconds are set to zero. Similarly, if your constructor takes arguments for year, month, date, hours, and minutes, then seconds and milliseconds are set to zero.
DateFormat and time
To create a DateFormat object to display time and date, you can use the static method getDateTimeInstance(int dateStyle, int timeStyle) . That method specifies the date and time styles you wish to use. If you are happy with the default styles, you can substitute the shorter getDateTimeInstance() .
To create a DateFormat object to display just the time, you can use the static method getTimeInstance(int timeStyle) .
The program below shows how the getDateTimeInstance() and getTimeInstance() methods work:
import java.util.*;
import java.text.*;
public class Apollo {
public static void main(String[] args) {
GregorianCalendar liftOffApollo11 = new GregorianCalendar(1969, Calendar.JULY, 16, 9, 32);
Date d = liftOffApollo11.getTime();
DateFormat df1 = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
DateFormat df2 = DateFormat.getTimeInstance(DateFormat.SHORT);
String s1 = df1.format(d);
String s2 = df2.format(d);
System.out.println(s1);
System.out.println(s2);
}
}
On my computer, the above program displays the following:
Jul 16, 1969 9:32:00 AM
9:32 AM
(Output can vary according to your computer's regional settings.)
Calculating elapsed time
You may sometimes need to calculate elapsed time; for instance, you may want to know the duration of a manufacturing process, given the starting and ending times. A rental company that rents items by the hour or day may also find it useful to calculate elapsed time. Similarly, in the financial world, it is often necessary to calculate interest payments over elapsed time.
To complicate the issue, humans calculate elapsed time in at least two ways. You can say that a day has gone by when 24 hours have elapsed, or when the calendar changes from one day to the next. I'll now discuss those two ways of thinking.
Elapsed time, case 1: Full units
In this case, a day has not elapsed until 24 hours have passed, an hour has not elapsed until 60 minutes have passed, a minute has not elapsed until 60 seconds have passed, and so on. Under this method, 23 hours of elapsed time would translate to zero days.
To calculate elapsed time this way, you start by calculating elapsed milliseconds. To do so, first convert each date to the number of milliseconds since the start of January 1, 1970. You then subtract the first millisecond value from the second millisecond value. Here is a sample calculation:
import java.util.*;
public class ElapsedMillis {
public static void main(String[] args) {
GregorianCalendar gc1 = new GregorianCalendar(1995, 11, 1, 3, 2, 1);
GregorianCalendar gc2 = new GregorianCalendar(1995, 11, 1, 3, 2, 2);
// the above two dates are one second apart
Date d1 = gc1.getTime();
Date d2 = gc2.getTime();
long l1 = d1.getTime();
long l2 = d2.getTime();
long difference = l2 - l1;
System.out.println("Elapsed milliseconds: " + difference);
}
}
The above program prints the following:
Elapsed milliseconds: 1000
That program also causes some confusion. The GregorianCalendar class's getTime() returns a Date object, while the Date class's getTime() method returns a long number representing the milliseconds before or after the beginning of January 1, 1970. So even though the methods have the same name, their return types are different!
You can convert milliseconds to seconds using simple integer division, as in the following code fragment:
long milliseconds = 1999;
long seconds = 1999 / 1000;
That way of converting milliseconds to seconds eliminates fractions, so 1,999 milliseconds equals 1 second, while 2,000 milliseconds equals 2 seconds.
To calculate larger units -- such as days, hours, and minutes -- given a number of seconds, you can use the following process:
Calculate the largest unit, reducing the number of seconds accordingly
Calculate the next largest unit, reducing the number of seconds accordingly
Repeat until only seconds remain
For example, if your elapsed time is 10,000 seconds, and you want to know how many hours, minutes, and seconds that value corresponds to, you start with the largest value: hours. Divide 10,000 by 3,600 (seconds in an hour) to calculate the number of hours. Using integer division, the answer is 2 hours (fractions are dropped in integer division). To calculate the remaining seconds, reduce 10,000 by 3,600 times 2 hours: 10,000 - (3,600 x 2) = 2,800 seconds. So you have 2 hours and 2,800 seconds.
To convert 2,800 seconds to minutes, divide 2,800 by 60 (seconds per minute). With integer division, the answer is 46. And 2,800 - (60 x 46) = 40 seconds. The final answer is 2 hours, 46 minutes, and 40 seconds.
The above calculation is shown in the following Java program:
import java.util.*;
public class Elapsed1 {
public void calcHMS(int timeInSeconds) {
int hours, minutes, seconds;
hours = timeInSeconds / 3600;
timeInSeconds = timeInSeconds - (hours * 3600);
minutes = timeInSeconds / 60;
timeInSeconds = timeInSeconds - (minutes * 60);
seconds = timeInSeconds;
System.out.println(hours + " hour(s) " + minutes + " minute(s) " + seconds + " second(s)");
}
public static void main(String[] args) {
Elapsed1 elap = new Elapsed1();
elap.calcHMS(10000);
}
}
Output from the above program is:
2 hour(s) 46 minute(s) 40 second(s)
The above program calculates the number of hours correctly, even when the elapsed time is less than an hour. For example, if you use the above program to calculate 1,000 seconds, the output is:
0 hour(s) 16 minute(s) 40 second(s)
To show a real-world example, the following program calculates elapsed time based on the Apollo 11 flight to the moon:
import java.util.*;
public class LunarLanding {
public long getElapsedSeconds(GregorianCalendar gc1, GregorianCalendar gc2) {
Date d1 = gc1.getTime();
Date d2 = gc2.getTime();
long l1 = d1.getTime();
long l2 = d2.getTime();
long difference = Math.abs(l2 - l1);
return difference / 1000;
}
public void calcHM(long timeInSeconds) {
long hours, minutes, seconds;
hours = timeInSeconds / 3600;
timeInSeconds = timeInSeconds - (hours * 3600);
minutes = timeInSeconds / 60;
System.out.println(hours + " hour(s) " + minutes + " minute(s)" );
}
public static void main(String[] args) {
GregorianCalendar lunarLanding = new GregorianCalendar(1969, Calendar.JULY, 20, 16, 17);
GregorianCalendar lunarDeparture = new GregorianCalendar(1969, Calendar.JULY, 21, 13, 54);
GregorianCalendar startEVA = new GregorianCalendar(1969, Calendar.JULY, 20, 22, 56);
GregorianCalendar endEVA = new GregorianCalendar(1969, Calendar.JULY, 21, 1, 9);
LunarLanding apollo = new LunarLanding();
long eva = apollo.getElapsedSeconds(startEVA, endEVA);
System.out.print("EVA duration = ");
apollo.calcHM(eva);
long lunarStay = apollo.getElapsedSeconds(lunarLanding, lunarDeparture);
System.out.print("Lunar stay = ");
apollo.calcHM(lunarStay);
}
}
Output from the above program is:
EVA duration = 2 hour(s) 13 minute(s)
Lunar stay = 21 hour(s) 37 minute(s)
So far, I have made calculations based on simple formulas like: "1 minute = 60 seconds," "1 hour = 60 minutes," and "1 day = 24 hours."
What about "1 month = ?


 

Read Tutorial at: Click here to view the tutorial

Rate Tutorial:
Working in Java time

View Tutorial:
Working in Java time

Related Tutorials:

GNU offers a new kind of Java IDE - JavaWorld - July 1998
GNU offers a new kind of Java IDE - JavaWorld - July 1998
 
Working in Java time
Working in Java time
 
XML documents on the run, Part 1
XML documents on the run, Part 1
 
Ilog JRules 4.0: Working by the rules
Ilog JRules 4.0: Working by the rules
 
Java is here to stay (JavaWorld / January 2000 / by John Rommel)
Java is here to stay (JavaWorld / January 2000 / by John Rommel)
 
Introduction to JavaServer Faces
This article is meant to acquaint the reader with JavaServer Faces, commonly known as JSF. JSF technology simplifies building the user interface for web applications. It does this by providing a higher-level framework for working with your web app, repres
 
Java programming dynamics, Part 7: Bytecode engineering with BCEL
Java programming dynamics, Part 7: Bytecode engineering with BCEL Apache BCEL lets you get to the details of JVM assembler language for classworking The Apache Byte Code Engineering Library (BCEL) lets you dig into the bytecode of Java classes. You
 
Good article on how to adopt XP
Good article on how to adopt XP xtreme programming (XP) is a software development methodology that makes coding the primary activity. By promoting values such as simplicity and feedback, XP allows Java programmers to incrementally develop and test applic
 
Prototyping Desktop Applications
Prototyping Desktop Applications a prototype can be used to gather user feedback very early in the development process. The prototype can also help you to estimate the time and resources needed to complete your project. It takes a lot of work to build a
 
Java Testing and Design
Java Testing and Java Test and Design is the companion to any book on Java software development practices, techniques, and testing. Software developers, QA analysts and IT managers working in large corporate IT groups, software development companies, and
 
The State of JAXB: Availability, Suitability, Analysis, and Architecture
The State of JAXB: Availability, Suitability, Analysis, and Architecture When working with XML in OO languages, there is little doubt that objects provide distinct advantages as compared to SAX, DOM, or raw XML. This process of working with XML and obj
 
new Version 0.9.3 of the Quake2 Java port Jake2
With the new Jake2 release 0.9.3 savegames are working. So you can take a break on your mission.
 
A Generic MVC Model in Java
A Generic MVC Model in Java Model-View-Controller (MVC) is a widely used design pattern, especially popular in graphical user interface (GUI) programming. JDK 1.5 introduces parameterized types, or generics. Combining the two allows for a generic imple
 
Mandarax
Mandarax is an open source java class library for deduction rules. It provides an infrastructure for defining, managing and querying rule bases.
 
When tears bring you back your beloved method...
Accessing platform-specific information hasn't always been easy. While you could certainly create processes with Runtime.exec(), dealing with differences across platforms to build parameter sets often led to headaches. In addition, the getenv() method of
 
JSPTags.com offers JSP developers a directory of resources.
JSPTags.com offers JSP developers a directory of resources related to JavaServer Pages, Servlets and Java. As the name JSPTags.com implies, special interest is given to JSP Tag Libraries. Many developers are working with and designing new JSP Tag Librarie
 
JSP Tutorial
This Tutorial is for beginners in the Java Server Pages Technology
 
Integrating Struts, Tiles, and JavaServer Faces
Integrating Struts, Tiles, and JavaServer Faces. Bring the power, flexibility, and manageability of the three technologies together.
 
Struts, JavaServer Faces, and Java Studio Creator:
The Evolution of Web Application Frameworks Sun Microsystems' Craig McClanahan, the creator of the Apache Struts Framework, co-specification lead for JavaServer Faces 1.0, and prime architect for Sun Java Studio Creator's new release, explains all three.
 
Roadmap to Sun Developer Documentation
This article offers an array of information sources about Sun products for developers, particularly those on docs.sun.com. Topics include the Solaris Operating System, Sun Studio tools, and other products and technologies.
 
Site navigation
 

 

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2006. All rights reserved.