Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Comparing two times

 
Kerry Shannon
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Creating a time entry screen for payroll. Trying to write the code to compare two (or more) times entered in the form (JSP/servlet) to determine the difference. I did not examples where you start with a form input string and compare to compute a difference in hours and minutes.
 
Angela Lamb
Ranch Hand
Posts: 156
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use DateFormat.parse(String text) to turn the form entries into Date objects. Date.getTime() will return a value of the time in milliseconds. You can compare the times to get the difference, then convert the milliseconds into minutes.
 
Kerry Shannon
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We will try your suggestions.
Editorial comment: I wish it was easier to work with dates, and I wish there were more examples of dates to strings and strings to dates. These are not new ideas. Someone has already done this.
 
Kerry Shannon
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
IT WORKS!!! We were able to do what you told us to do.
Thank you!
 
rani bedi
Ranch Hand
Posts: 358
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you please tell me how you did it because when i tried to use
java.util.Date date1 = java.text.DateFormat.parse(args[0])
it gives an error
Can't make static reference to method java.util.Date parse(java.lang.String) in class java.text.DateFormat.
java.util.Date date1 = java.text.DateFormat.parse(args[0]);
 
Kerry Shannon
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We have a form coming in from the employee who entered StartTime.
First, we display from the database if it was previously saved:
if (time.getDStartTime() != null)
{ StartTime = tmShort.format(time.getDStartTime()); }

Then, we paint the time entry form:
<td ><input type="text" name="StartTime" value="<%=StartTime%>"></td>
Then, we used the suggestion to get the value of the time they entered:
<%<br /> long starttime = time.getDStartTime().getTime();
 
Angela Lamb
Ranch Hand
Posts: 156
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Parmeet, you need to create an instance of the DateFormat class first. The parse method is not static. You can use the getDateInstance(), getTimeInstance(), or getDateTimeInstance() methods. The API explains all of these options in detail.

http://java.sun.com/j2se/1.3.0/docs/api/java/text/DateFormat.html
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic