好的 - 我的第一篇StackOverflow帖子:我希望它不太荒谬。我正在尝试做一些非常基本的事情:采用两个类似格式的字符串,使用相同的SimpleDateFormat将它们转换为日期,然后将差异看作长。在这里发布整个来源:
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateCompare {
public static void main(String[] args){
DateCompare dc = new DateCompare();
try {
long diff = dc.compare("2012-03-15T10:00:00.0Z",
"2012-03-15T10:44:56.1031157730031Z");
System.out.println("Difference: "+diff);
} catch (ParseException e) {
e.printStackTrace();
}
}
private long compare(String first,String second) throws ParseException{
System.out.println(first);
System.out.println(second);
Date firstDate = datify(first);
System.out.println(firstDate.toString());
Date nextDate = datify(second);
System.out.println(nextDate.toString());
return(compare(firstDate,nextDate));
}
private Date datify(String in){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSSSSSS'Z'");
Date theDate = sdf.parse(in,new ParsePosition(0));
return(theDate);
}
private long compare(Date first,Date second){
long diff=0;
if (first.after(second)){
diff = first.getTime()-second.getTime();
}
else{
diff = second.getTime()-first.getTime();
}
return(diff);
}
}
和结果:
2012-03-15T10:00:00.0Z
2012-03-15T10:44:56.1031157730031Z
Thu Mar 15 10:00:00 EDT 2012
Mon Mar 19 16:17:54 EDT 2012
差异:368274991
对我毫无意义;任何线索都将是一个巨大的帮助...