日期:2014-05-17  浏览次数:20829 次

java关于时间的比较问题。
现在传递过来的参数是:

String time="2012-05-12,18:00";

现在需要进行判断,这个时间是在,

是否在2012-05-12的17:00之后否?
如果是,又需要判断,是否在
2012-05-12的17:00-00:00加上2012-05-13的00:01-8:00

或者是在
2012-05-13的8:01-12:00
或者是在
2012-05-13的12:01-17:00

这三个时间段的那个时间段了?


希望给出具体的代码,因为,实际上我已经看了java.text.format和java.util.date的apl,没看懂。
如果方便的话,也可以稍微给我解释下,关于java的日期处理,感觉完全看不懂。

------解决方案--------------------
Java code
String time="2012-05-12,18:00";
DateFormat f= new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date date = f.parse(time);
Date date2 = f.parse("2012-05-13 8:01");
int i = date.compareTo(date2);
/*the value 0 if the argument Date is equal to this Date;
a value less than 0 if this Date is before the Date argument; 
and a value greater than 0 if this Date is after the Date argument.*/

//date.before(date2);
//date.after(date2);

------解决方案--------------------
package leedp.login;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateCompare {
public static void main(String[] args) throws ParseException {
/*
* the value 0 if the argument Date is equal to this Date; a value less
* than 0 if this Date is before the Date argument; and a value greater
* than 0 if this Date is after the Date argument.
*/
String time = "2012-05-12,18:00";
time = time.replace(",", " ");
DateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date date1 = f.parse(time);
Date date2 = f.parse("2012-05-13 8:01");
int i = date1.compareTo(date2);
System.out.println(i);
Calendar c = Calendar.getInstance();
Date date = null;
try {
date = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse("2012-05-12 18:00");
} catch (ParseException e) {
e.printStackTrace();
}
c.setTime(date);
int day = c.get(Calendar.DATE);
c.set(Calendar.DATE, day - 1);

String dayBefore = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(c
.getTime());
System.out.println(dayBefore);

}

}

------解决方案--------------------
探讨
那我想在请问一下,如果现在的时间是个变量,就比如是当天,那前面那个比较,就是当天的前一天,如何获取,当天的前一天了?比如,今天是2012-05-12,18:00昨天就是2012-05-11,18:00如何获取这个时间了?

------解决方案--------------------
具体代码你自己会写的,简单说就是将string转成date,在java里面date类型可以直接比较的。