跟日期 时间有关的计算与比较

来源:互联网 发布:新疆移动4g网络什么时候开通 编辑:程序博客网 时间:2024/05/17 20:51
/**
* 计算N年之后的日期
* */
public Date calDateByNum(int num){
Date date = new Date();
Calendar cld = Calendar.getInstance();
cld.setTime(date);
cld.add(Calendar.YEAR, num);
return cld.getTime();
}
/**
* 时间差转为小时数
* @throws ParseException 
*/
public double calDateToHours(String beg,String end) throws ParseException{
SimpleDateFormat sdf =   new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d1 = sdf.parse(beg);
Date d2 = sdf.parse(end);
d1.setYear(2015);
d1.setMonth(11);
d1.setDate(11);
d2.setYear(2015);
d2.setMonth(11);
d2.setDate(11);
long m1 = d1.getTime();
long m2 = d2.getTime();
long n = m2 - m1;
double t = (double)n/3600000;
String str = t+"";
if(str.length()>=4){
str = str.substring(0, 4);
}
return Double.parseDouble(str);
}
/***
* 计算两个日期之间的年数
*/
public double calDateToYears(String end,String beg) {
SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");    
        double day = 0;
        double year = 0;
        try {    
         Date date = myFormatter.parse(end);    
         Date mydate = myFormatter.parse(beg);    
         day = (date.getTime() - mydate.getTime()) / (24 * 60 * 60 * 1000);    
         year =  day/365;
String str = year+"";
if(str.length()>=4){
year = Double.parseDouble(str.substring(0, 4));
}
        } catch (Exception e) {     
        }    
        return year;   
}
/***
* 返回当前系统日期+时间
*/
public String systemTime() {
Date now = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return dateFormat.format(now);
}
/***
* 获取当前的星期数
*/
public int getNowWeek() {
Calendar cal = Calendar.getInstance();
return cal.get(Calendar.DAY_OF_WEEK)-1;
}
/**

* 获取当前的时间
*/
public String getNowTime() {
Date now = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
return dateFormat.format(now);
}
/**
* 把日期转为时间
*/
public String dateToTime(Date date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
return dateFormat.format(date);
}
/**
* 开始时间跟结束时间作比较,如果结束时间大返回1;否则返回0
* @param beg
* @param end
*/
public int compareTime(Date beg,Date end){
SimpleDateFormat f = new SimpleDateFormat("HHmmss"); //格式化为 hhmmss
int d1Number = Integer.parseInt(f.format(beg).toString()); //将第一个时间格式化后转为int
int d2Number = Integer.parseInt(f.format(end).toString()); //将第二个时间格式化后转为int
if(d1Number>d2Number){
return 0;
}
else{
return 1;
}
}
0 0