Skip to content

Instantly share code, notes, and snippets.

@X-Bird
Created October 17, 2014 14:07
Show Gist options
  • Save X-Bird/da5ff71326a5dab97fb7 to your computer and use it in GitHub Desktop.
Save X-Bird/da5ff71326a5dab97fb7 to your computer and use it in GitHub Desktop.
js算生肖
// JS帮你计算属相
// 背景:一个人出生在2014年的正月初一,他的生肖到底是属蛇还是属马呢?这就要确定那一天才是一年的开始。是春节还是立春?每年的春节是正月初一,但是生肖必须是从立春日开始计算。春节是1912年孙中山先生废除旧历,采用公元纪年之后的1914年,时任民国大总统的袁世凯颁布法令,每年的正月初一是春节,在此之前传统上都是以二十四节气的立春作为岁首。综上所属,2014年正月初一出生的应该是属蛇。
// 既然知道了每年的立春日才是真正的生肖判断标准,那么怎么才能获取每年的立春日是多少呢?
// 网上有这么一个计算立春日的公式:[Y*D+C]-L
// 公式解读:Y:年数的后2位 D:常量0.2422 C:世纪值,21世纪是3.87 取整数减 L:闰年数。
// 举例说明:2058年立春日期的计算步骤[58×.0.2422+3.87]-[(58-1)/4]=17-14=3,则2月3日立春
// 这里提供JS计算每年立春日和生肖的接口,源码如下:
/**
* 该方法只能正确判定到2099年
* @auther 黑MAO
* @time 2014年7月19日
*/
;(function(window){
/**
* 生肖构造函数,默认参数是当前日期
* @param {Number} year 年
* @param {Number} month 月
* @param {Number} day 日
*/
function Zodiac(year, month, day) {
var date = new Date();
this.year = year*1 || date.getFullYear();
this.month = month*1 || date.getMonth();
this.day = day*1 || date.getDate();
}
Zodiac.constructor = Zodiac;
/**
* 获取C值
* @return {Number} C
*/
Zodiac.prototype.getC = function(){
var _year = Math.floor(this.year/100)+1;
var C;
switch(_year){
case 20:
C = 4.6295;
break;
case 21:
C = 3.87;
break;
case 22:
C = 4.15;
break;
default:
C = 3.87;
}
return C;
}
/**
* 获取立春日 一般都在2月
* @return {Number} springDay
*/
Zodiac.prototype.getSpringDay = function(){
var Y = this.year%100,
D = 0.2422,
C = this.getC(),
L = (Y-1)/4,
springDay = 0;
springDay = Math.floor(Y*D+C)-Math.floor((Y-1)/4);
return springDay;
}
/**
* 获取生肖
* @return {String} myZodiac
*/
Zodiac.prototype.getZodiac = function(){
var year = this.year,
month = this.month,
day = this.day,
zodiac = ['子鼠','丑牛','寅虎','卯兔','辰龙','巳蛇','午马','未羊','申猴','酉鸡','戌狗','亥猪'],
myPos = (year-1900)%12,
myZodiac = zodiac[myPos],
springDay = this.getSpringDay();
switch(month){
case 1:
var _myPos = myPos-1;
if(_myPos<0){
_myPos = 11;
}
myZodiac = zodiac[_myPos];
break;
case 2:
if(day < springDay){
var _myPos = myPos-1;
if(_myPos<0){
_myPos = 11;
}
myZodiac = zodiac[_myPos];
}
break;
}
return myZodiac;
}
window.Zodiac = Zodiac;
})(window);
  
// 使用方法:
//默认参数是当前日期
var zodiac = new Zodiac();
//var zodiac = new Zodiac(1980, 2, 3);
//获取立春日
console.log(zodiac.getSpringDay());
//获取生肖
console.log(zodiac.getZodiac());
//可以与万年历进行比对
for(var year = 1900; year < 2100; year++) {
var zodiac = new Zodiac(year, 2, 4);
console.log(year, zodiac.getSpringDay(),zodiac.getZodiac());
}
// 可以计算你的真正生肖了~~
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment