首页 > 代码库 > Date()日期简单计算

Date()日期简单计算

    /**

     * 判断是否为闰年

     * @param year

     * @return

     */

    public boolean isLeap ( int year )

    {

        if ( (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) )

            return true;

        else

            return false;

    }

  /**

     * 判断某年某月总天数

     * @param year

     * @param month

     * @return

     */

    public int getDays ( int year , int month )     {

        int tianshu = 0;

        switch (month)

        {

            case 1:

            case 3:

            case 5:

            case 7:

            case 8:

            case 10:

            case 12:

                tianshu = 31;

                break;

            case 4:

            case 6:

            case 9:

            case 11:

                tianshu = 30;

                break;

            case 2:

                if ( isLeap(year) == true )

                {

                    tianshu = 29;

                }

                else

                {

                    tianshu = 28;

                }

                break;

        }

        return tianshu;

    }

    /**

     * 在某Date()日期上增加几天或几个月

     * @return 新的日期

     */

 public static String changeDate(String str, int n) {

  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

  try {

   Calendar cd = Calendar.getInstance();

   cd.setTime(sdf.parse(str));

   cd.add(Calendar.DATE, n); // 在审批基础上增加一天

   // cd.add(Calendar.MONTH, n);//增加一个月

   return sdf.format(cd.getTime());

  } catch (Exception e) {

   Global.getInstance().LogError(e);

   return str;

  }

 }

 //两个Date()相加减

 public static void main(String[] args) {

     try {

   SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd");

   Date begin=dfs.parse("1992-08-10");

   Date end =  new Date();

   long between=(end.getTime()-begin.getTime())/1000;//除以1000是为了转换成秒

   long day1=between/(24*3600);       //几天

   long hour1=between%(24*3600)/3600; //零几小时

   long minute1=between%3600/60;      //零几分钟

   long second1=between%60/60;        //零几秒钟

} catch (ParseException e) {

   e.printStackTrace();

}

 }

 //输入某人生日计算实际年龄

 public static int getAge(String date) {

  try {

   SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd");

   Date begin = dfs.parse(date);

   int month = begin.getMonth() + 1;

   int day = begin.getDate();

   Date end = new Date();

   long between = (end.getTime() - begin.getTime()) / 1000;

   long day1 = between / (24 * 3600);

   int age = (int) (day1 / 365);

   long nmonth = end.getMonth() + 1;

   long nday = end.getDate();

   if (nmonth < month || (nmonth == month && day < nday)) {

    age--;

   }

   return age;

  } catch (Exception e) {

   e.printStackTrace();

   return 0;

  }

 }