转自:https://blog.****.net/iteye_8535/article/details/82246006
JAVA时间进行比较和转换,时间加减得到天数
1. 把时间类型的字符串转为DATE
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Text {
public static void main(String[] args){
SimpleDateFormat dd=new SimpleDateFormat("yyyy-MM-dd");
String d=dd.format(new Date());
System.out.print(d);
try {
Date date=dd.parse("2007-12-12");
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
2.把时间类型的整型转为DATE
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Text {
public static void main(String[] args){
SimpleDateFormat dd=new SimpleDateFormat("yyyyMMdd");
String d=dd.format(new Date());
System.out.print(d);
int ddd=20071212;
try {
Date date=dd.parse(ddd+"");
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
3.时间比较大小
java.util.Date nowdate=new java.util.Date();
String myString = "2008-09-08";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd", Locale.CHINA);
Date d = sdf.parse(myString);
boolean flag = d.before(nowdate);
if(flag)
System.out.print("早于今天")
else
System.out.print("晚于今天")
4.时间加减得到天数
* @param beginDateStr
* @param endDateStr
* @return
* long
* @author Administrator
*/
public static long getDaySub(String beginDateStr,String endDateStr)
{
long day=0;
java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd");
java.util.Date beginDate;
java.util.Date endDate;
try
{
beginDate = format.parse(beginDateStr);
endDate= format.parse(endDateStr);
day=(endDate.getTime()-beginDate.getTime())/(24*60*60*1000);
//System.out.println("相隔的天数="+day);
} catch (ParseException e)
{
// TODO 自动生成 catch 块
e.printStackTrace();
}
return day;
}