java 计算瑞年的方法

摘要: 任何语言都有可能计算某一年是否为瑞年的方法,也就是说一年有 366 天,每隔4 年就出现一次。最基本的算法如下:代码片段, 请查看文章详情 ...

任何语言都有可能计算某一年是否为瑞年的方法,也就是说一年有 366 天,每隔4 年就出现一次。最基本的算法如下:

if year is divisible by 400 then
   is_leap_year
else if year is divisible by 100 then
   not_leap_year
else if year is divisible by 4 then
   is_leap_year
else
   not_leap_year


知道了这个基本算法,那么起始与语言无关了,这里就用JAVA 语言做一个讲解
public class DateTimeExample {
 
    public static void main(String[] args) {
 
	DateTimeExample obj = new DateTimeExample();
	System.out.println("1993 is a leap year : " + obj.isLeapYear(1993));
	System.out.println("1996 is a leap year : " + obj.isLeapYear(1996));
	System.out.println("2012 is a leap year : " + obj.isLeapYear(2012));
 
    }
 
    public boolean isLeapYear(int year) {
 
	if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) {
		return true;
	} else {
		return false;
	}
    }
 
}


输出结果如下

1993 is a leap year : false
1996 is a leap year : true
2012 is a leap year : true


当然,起始用Calendar 也是可以计算出来的.
 import java.util.GregorianCalendar;
 
    //...
    public boolean isLeapYear(int year) {
 
	GregorianCalendar cal = (
		GregorianCalendar) GregorianCalendar.getInstance();
 
	return cal.isLeapYear(year);
    }

上一篇: java 任意两个时间差,天数,小时数,分钟数,秒数
下一篇: Django 中 如何使用 settings.py 中的常量
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号