常用日期解决方案

来源:互联网 发布:哈工大深圳知乎 编辑:程序博客网 时间:2024/05/01 06:58
          当前日期加一个月 :
          Calendar a = Calendar.getInstance();
          a.add(Calendar.MONTH,1);
          long sdate=a.getTimeInMillis();
          java.sql.Date sdate1=new java.sql.Date(sdate);
          System.out.println(sdate1);


        得到当前日期和以前日期之间的天数 :
        public static int getTodayCount(Date oldDate) {
        long day = 1000 * 60 * 60 * 24;
        Date today = new Date();
        long todayTime = today.getTime();
        long oldTime = oldDate.getTime();
        int result = (int) ((todayTime - oldTime) / day + 1);

        return result;
        }

        构造一个日历:
       public static int[][] buildCalendar(Calendar cal) {
        cal.set(Calendar.DAY_OF_MONTH, 1);
        int firstDateInWeek = cal.get(Calendar.DAY_OF_WEEK) - 1;
        int dateOfMonth = getMonthDateCount(cal);
        int base = dateOfMonth + firstDateInWeek;
        int row = base / 7;
        row += ((base % 7) > 0) ? 1 : 0;
        int[][] cals = new int[row][7];
        int iCol = firstDateInWeek, iRow = 0;
        for (int i = 1; i <= dateOfMonth; i++) {
            cals[iRow][iCol] = i;
            if (iCol == 6) {
                iCol = 0;
                iRow++;
            } else
                iCol++;
        }
        return cals;
    }

        得到这个月的天数:
       public static int getMonthDateCount(Calendar cal) {
        Calendar cal2 = (Calendar) cal.clone();
        cal2.add(Calendar.MONTH, 1);
        cal2.set(Calendar.DAY_OF_MONTH, 1);
        cal2.add(Calendar.DAY_OF_MONTH, -1);
        return cal2.get(Calendar.DAY_OF_MONTH);
    }
原创粉丝点击