Charles Bell
Posts: 519
Nickname: charles
Registered: Feb, 2002
|
|
Re: Trying to write a date program
|
Posted: Aug 3, 2003 12:26 PM
|
|
The following is an example of using SimpleDateFormat
/* DateDifference.java
* June 21, 2003
*/
import java.text.*;
import java.util.*;
/** How to determine the difference between two dates formatted as follows:
* 6/16/2003 06:30:35
* 6/16/2003 06:31:37
*/
public class DateDifference{
public static void main(String[] args){
new DateDifference();
}
public void test(){
String first = "6/16/2003 06:30:35";
String second = "6/16/2003 06:31:37";
Date firstDate = getDate(first);
Date secondDate = getDate(second);
System.out.println("firstDate: " + firstDate.toString());
System.out.println("secondDate: " + secondDate.toString());
System.out.println("Difference in milliseconds: " + getDifference(first, second));
}
/** Returns the difference in milliseconds between two dates formatted as:
* 6/16/2003 06:30:35
* 6/16/2003 06:31:37
*/
public long getDifference(String first, String second){
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
Date firstDate = format.parse(first, new ParsePosition(0));
Date secondDate = format.parse(second, new ParsePosition(0));
return Math.abs(firstDate.getTime() - secondDate.getTime());
}
/** Returns a java.util.Date from a string formatted as:
* 6/16/2003 06:30:35
*/
public Date getDate(String dateString){
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
return format.parse(dateString, new ParsePosition(0));
}
}
|
|