Java对时间操作的一些封装函数

 

1. 计算两天之间相隔几天的Java函数

/** * 计算两天之间相差几天 * @param startTime * @param endTime * @return * * 取得两个时间段的时间间隔 * return t2 与t1的间隔天数 * throws ParseException 如果输入的日期格式不是0000-00-00 格式抛出异常 */ public static int betweenTwoDays(String startTime,String endTime){ String startYearStr = startTime.substring(0, 4); String endYearStr = endTime.substring(0, 4); String startMonthStr = startTime.substring(4, 6); String endMonthStr = endTime.substring(4, 6); String startDayStr = startTime.substring(6, 8); String endDayStr = endTime.substring(6, 8); String t1 = startYearStr+"-"+startMonthStr+"-"+startDayStr; String t2 = endYearStr+"-"+endMonthStr+"-"+endDayStr; DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); int betweenDays = 0; Date d1 = null; Date d2 = null; try { d1 = format.parse(t1); d2 = format.parse(t2); Calendar c1 = Calendar.getInstance(); Calendar c2 = Calendar.getInstance(); c1.setTime(d1); c2.setTime(d2); int betweenYears = c2.get(Calendar.YEAR)-c1.get(Calendar.YEAR); betweenDays = c2.get(Calendar.DAY_OF_YEAR)-c1.get(Calendar.DAY_OF_YEAR); for(int i=0;i<betweenYears;i++){ c1.set(Calendar.YEAR,(c1.get(Calendar.YEAR)+1)); betweenDays += c1.getMaximum(Calendar.DAY_OF_YEAR); } } catch (ParseException e) { e.printStackTrace(); } return betweenDays; }

 

 

2. 判断是否为闰年

 

/*** * 判断是否为闰年 * @param yearStr * @return */ public static boolean isLoop(String yearStr){ int year = Integer.parseInt(yearStr); boolean flag = false; if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)){ flag = true; } return flag; } public static boolean isLoop(int year){ boolean flag = false; if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)){ flag = true; } return flag; }

 

3.判断前多少天是那一天的函数

/**** * 计算出day的before天之前是哪一天 * @param day * @return */ public static String getDayBefore(String day,int beforeDay){ String resultDay = null; String YearStr = day.substring(0, 4); String MonthStr = day.substring(4, 6); String DayStr = day.substring(6, 8); int yearInt = Integer.parseInt(YearStr); int monthInt = Integer.parseInt(MonthStr); int dayInt = Integer.parseInt(DayStr); int[] month; if(isLoop(yearInt)){ month = new int[]{0,31,29,31,30,31,30,31,31,30,31,30,31}; } else{ month = new int[]{0,31,28,31,30,31,30,31,31,30,31,30,31}; } for(int i=0;i<beforeDay;i++){ dayInt--; if(dayInt<=0){ monthInt--; if(monthInt<=0){ yearInt--; monthInt = 12; dayInt = month[monthInt]; } else{ dayInt = month[monthInt]; } } } resultDay = ""+yearInt+String.format("%02d",monthInt)+String.format("%02d",dayInt); return resultDay; }

 

 

一些转载之作:

1.计算某一月份的最大天数
Calendar time=Calendar.getInstance(); 
time.clear(); 
time.set(Calendar.YEAR,year); 
time.set(Calendar.MONTH,i-1);//注意,Calendar对象默认一月为0             
int day=time.getActualMaximum(Calendar.DAY_OF_MONTH);//本月份的天数
注:在使用set方法之前,必须先clear一下,否则很多信息会继承自系统当前时间
2.Calendar和Date的转化
(1) Calendar转化为Date
Calendar cal=Calendar.getInstance();
Date date=cal.getTime();
(2) Date转化为Calendar
Date date=new Date();
Calendar cal=Calendar.getInstance();
cal.setTime(date);
3.格式化输出日期时间
Date date=new Date();
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
System.out.println(df.format(date));
4.计算一年中的第几星期
(1)计算某一天是一年中的第几星期
Calendar cal=Calendar.getInstance();
cal.set(Calendar.YEAR, 2006);
cal.set(Calendar.MONTH, 8);
cal.set(Calendar.DAY_OF_MONTH, 3);
int weekno=cal.get(Calendar.WEEK_OF_YEAR);
(2)计算一年中的第几星期是几号
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
Calendar cal=Calendar.getInstance();
cal.set(Calendar.YEAR, 2006);
cal.set(Calendar.WEEK_OF_YEAR, 1);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println(df.format(cal.getTime()));
输出:
2006-01-02
5.add()和roll()的用法
(1)add()方法
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
Calendar cal=Calendar.getInstance();
cal.set(Calendar.YEAR, 2006);
cal.set(Calendar.MONTH, 8);
cal.set(Calendar.DAY_OF_MONTH, 3);
cal.add(Calendar.DATE, -4);
Date date=cal.getTime();
System.out.println(df.format(date));
cal.add(Calendar.DATE, 4);
date=cal.getTime();
System.out.println(df.format(date));
输出:
    2006-08-30
    2006-09-03
(2)roll方法
cal.set(Calendar.YEAR, 2006);
cal.set(Calendar.MONTH, 8);
cal.set(Calendar.DAY_OF_MONTH, 3);
cal.roll(Calendar.DATE, -4);
date=cal.getTime();
System.out.println(df.format(date));
cal.roll(Calendar.DATE, 4);
date=cal.getTime();
System.out.println(df.format(date));
输出:
    2006-09-29
    2006-09-03
可见,roll()方法在本月内循环,一般使用add()方法;
6.计算两个任意时间中间的间隔天数
(1)传进Calendar对象

/**计算两个时间之间相隔天数
     * 
@param startday  开始时间
     * 
@param endday 结束时间
     * 
@return
     
*/

    
public   int  getIntervalDays(Calendar startday,Calendar endday) {
        
//确保startday在endday之前
        if(startday.after(endday)){
            Calendar cal
=startday;
            startday
=endday;
            endday
=cal;
        }

        
//分别得到两个时间的毫秒数
        long sl=startday.getTimeInMillis();
        
long el=endday.getTimeInMillis();
        
        
long ei=el-sl;    
        
//根据毫秒数计算间隔天数
        return (int)(ei/(1000*60*60*24));
    }
(2)传进Date对象
/**计算两个时间之间相隔天数
     * 
@param startday  开始时间
     * 
@param endday 结束时间
     * 
@return
     
*/

    
public   int  getIntervalDays(Date startday,Date endday) {
        
//确保startday在endday之前
        if(startday.after(endday)){
            Date cal
=startday;
            startday
=endday;
            endday
=cal;
        }

        
//分别得到两个时间的毫秒数
        long sl=startday.getTime();
        
long el=endday.getTime();
        
        
long ei=el-sl;    
        
//根据毫秒数计算间隔天数
        return (int)(ei/(1000*60*60*24));
    }
同理,可以用相同的方法计算出任意两个时间相隔的小时数,分钟数,秒钟数等
注:以上方法是完全按时间计算,有时并不能令人满意,如:
startday="2006-10-11 20:00:00"
endday="2006-10-12 8:00:00"
计算结果为0,但是我们也许相让计算结果变为1,此时可以用如下方法实现:
在传参之前,先设定endday的时间,如:
        endday.set(Calendar.HOUR_OF_DAY, 23);
         endday.set(Calendar.MINUTE, 59);
        endday.set(Calendar.SECOND, 59);
        endday.set(Calendar.MILLISECOND, 59);
这样再传进去startday,endday,则结果就如我们所愿了。不过,如果嫌以上方法麻烦,可以参考以下方法:
(3)改进精确计算相隔天数的方法
     public   int  getDaysBetween (Calendar d1, Calendar d2)  {
        
if (d1.after(d2)) {  // swap dates so that d1 is start and d2 is end
            java.util.Calendar swap = d1;
            d1 
= d2;
            d2 
= swap;
        }

        
int days = d2.get(Calendar.DAY_OF_YEAR) - d1.get(Calendar.DAY_OF_YEAR);
        
int y2 = d2.get(Calendar.YEAR);
        
if (d1.get(Calendar.YEAR) != y2) {
            d1 
= (Calendar) d1.clone();
            
do {
                days 
+= d1.getActualMaximum(Calendar.DAY_OF_YEAR);//得到当年的实际天数
                d1.add(Calendar.YEAR, 1);
            }
 while (d1.get(Calendar.YEAR) != y2);
        }

        
return days;
    }

你可能感兴趣的:(java,c,Date,String,calendar)