java日期的一些处理

来源:互联网 发布:360浏览器mac版 编辑:程序博客网 时间:2024/05/17 22:29

日期的格式化,提供简单的几种格式

private final static SimpleDateFormatsdfYear =new SimpleDateFormat("yyyy");

 

private final static SimpleDateFormatsdfDay =new SimpleDateFormat(

"yyyy-MM-dd");

private final static SimpleDateFormatsdfDays =new SimpleDateFormat(

"yyyyMMdd");

 

private final static SimpleDateFormatsdfTime =new SimpleDateFormat(

"yyyy-MM-dd HH:mm:ss");

 

sdfYear .format(new Date());


计算日期,计算几个月或者几天之后的日期


日期的加法操作,以月为单位

Calendar now = Calendar.getInstance();

now.add(Calendar.MONTH,3);      //三个月之后的日期

Date expireDate=now.getTime();

日期的加法操作,以为单位

Calendar now = Calendar.getInstance();

now.add(Calendar.DAY_OF_YEAR,30);     //30天之后的日期

Date expireDate=now.getTime();



得到某个时间段内的所有月份,用于判断套餐是否到期

DateFormat  sdf=new SimpleDateFormat("yyyy-MM-dd"); 

List  arrayList=new ArrayList();

Calendar cal = Calendar.getInstance(); 

Calendar cal1 = Calendar.getInstance();

String bdate="开始时间";

String  sdate="结束时间";

cal.setTime(sdf.parse(bdate));  

cal1.setTime(sdf.parse(sdate));

arrayList.add(bdate);

     while (true) {  

           //日期加一  

        cal.add(Calendar.MONTH, 1);  

           //日期加一后判断是否达到了结束日期,达到则终止打印  

           if (cal.compareTo(cal1) == 0) {  

            break;  

           }

          arrayList.add(sdf.format(cal.getTime()));

        }

cal.getTime():可以得到时间


比较两个日期的大小

/**

 * 获取YYYY-MM-DD HH:mm:ss格式

     * 比较两个日期的前后顺序

     * lgb

     * @param DATE1

     * @param DATE2

     * @return 0.两个日期一样      1.dt1dt2前    2.dt1dt2后    

     */

    public static int compare_date(StringDATE1, StringDATE2) {

        DateFormat df =new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");

        try {

            Date dt1 =df.parse(DATE1);

            Date dt2 =df.parse(DATE2);

            if (dt1.getTime() >dt2.getTime()) {

                return 1;

            } else if (dt1.getTime() < dt2.getTime()) {

                return -1;

            } else {

                return 0;

            }

        } catch (Exceptionexception) {

            exception.printStackTrace();

        }

        return 0;

}


原创粉丝点击