ChineseCalendar.cs 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace Masuit.Tools.DateTimeExt
  5. {
  6. /// <summary>
  7. /// 中国农历类 支持 1900.1.31日起至 2069.12.31日止的数据
  8. /// </summary>
  9. /// <remarks>
  10. /// 本程序使用数据来源于网上的万年历查询,并综合了一些其它数据
  11. /// </remarks>
  12. public class ChineseCalendar
  13. {
  14. private class ChineseCalendarException(string msg) : Exception(msg);
  15. private readonly DateTime _datetime;
  16. #region 基础数据
  17. private const int MinYear = 1900;
  18. private const int MaxYear = 2100;
  19. private static readonly DateTime MinDay = new DateTime(1900, 1, 30);
  20. private const int GanZhiStartYear = 1864; //干支计算起始年
  21. private static readonly DateTime GanZhiStartDay = new DateTime(1899, 12, 22); //起始日
  22. private const string HzNum = "零一二三四五六七八九";
  23. private const int AnimalStartYear = 1900; //1900年为鼠年
  24. private static readonly DateTime ChineseConstellationReferDay = new DateTime(2007, 9, 13); //28星宿参考值,本日为角
  25. /// <summary>
  26. /// 来源于网上的农历数据
  27. /// </summary>
  28. /// <remarks>
  29. /// 数据结构如下,共使用17位数据<br/>
  30. /// 说明如下:<br/>
  31. ///1-4:判断当年是否为闰年,若为闰年,则为闰年的月份,反之为0;<br/>
  32. ///5-16:为除了闰月外的正常月份是大月还是小月,1为30天,0为29天。(注意:1月对应第16位,2月对应第15位……12月对应第5位)<br/>
  33. ///17-20: 表示闰月是大月还是小月,若为1,则为大月,若为0,则为小月。(注意:仅当存在闰月的情况下有意义)<br/>
  34. /// -<br/>
  35. ///举例说明:<br/>
  36. ///例一:0x04bd8<br/>
  37. ///对应二进制:0000 0100 1011 1101 1000<br/>
  38. ///则表示当年有闰月8月,且闰月为小月29天<br/>
  39. ///该年1-12月的天数为:29 30 29 29 30 29 30 29(闰月) 30 30 29 30<br/>
  40. ///例二:0x04ae0<br/>
  41. ///对应二进制:0000 0100 1010 1110 0000<br/>
  42. ///则表示当年没有闰月<br/>
  43. ///该年1-12月的天数为:29 30 29 29 30 29 30 29 30 30 30 29<br/>
  44. ///补充闰月介绍:<br/>
  45. ///闰月是阴阳历中为使历年平均长度接近会归年而增设的月。阴阳历以朔望月的长度(29.5306日)为一个月的平均值,全年12个月,同回归年(365.2422日)相差约10日21时,故需要置闰,三年闰一个月,五年闰二个月,十九年闰七个月。阴阳历以朔望月的长度(29.5306日)为一个月的平均值,全年12个月,同回归年(365.2422日)相差约10日21时,故需要置闰,三年闰一个月,五年闰二个月,十九年闰七个月。
  46. ///</remarks>
  47. private static readonly int[] LunarDateArray =
  48. {
  49. 0x04BD8, 0x04AE0, 0x0A570, 0x054D5, 0x0D260, 0x0D950, 0x16554, 0x056A0, 0x09AD0, 0x055D2, 0x04AE0,
  50. 0x0A5B6, 0x0A4D0, 0x0D250, 0x1D255, 0x0B540, 0x0D6A0, 0x0ADA2, 0x095B0, 0x14977, 0x04970, 0x0A4B0,
  51. 0x0B4B5, 0x06A50, 0x06D40, 0x1AB54, 0x02B60, 0x09570, 0x052F2, 0x04970, 0x06566, 0x0D4A0, 0x0EA50,
  52. 0x06E95, 0x05AD0, 0x02B60, 0x186E3, 0x092E0, 0x1C8D7, 0x0C950, 0x0D4A0, 0x1D8A6, 0x0B550, 0x056A0,
  53. 0x1A5B4, 0x025D0, 0x092D0, 0x0D2B2, 0x0A950, 0x0B557, 0x06CA0, 0x0B550, 0x15355, 0x04DA0, 0x0A5B0,
  54. 0x14573, 0x052B0, 0x0A9A8, 0x0E950, 0x06AA0, 0x0AEA6, 0x0AB50, 0x04B60, 0x0AAE4, 0x0A570, 0x05260,
  55. 0x0F263, 0x0D950, 0x05B57, 0x056A0, 0x096D0, 0x04DD5, 0x04AD0, 0x0A4D0, 0x0D4D4, 0x0D250, 0x0D558,
  56. 0x0B540, 0x0B6A0, 0x195A6, 0x095B0, 0x049B0, 0x0A974, 0x0A4B0, 0x0B27A, 0x06A50, 0x06D40, 0x0AF46,
  57. 0x0AB60, 0x09570, 0x04AF5, 0x04970, 0x064B0, 0x074A3, 0x0EA50, 0x06B58, 0x055C0, 0x0AB60, 0x096D5,
  58. 0x092E0, 0x0C960, 0x0D954, 0x0D4A0, 0x0DA50, 0x07552, 0x056A0, 0x0ABB7, 0x025D0, 0x092D0, 0x0CAB5,
  59. 0x0A950, 0x0B4A0, 0x0BAA4, 0x0AD50, 0x055D9, 0x04BA0, 0x0A5B0, 0x15176, 0x052B0, 0x0A930, 0x07954,
  60. 0x06AA0, 0x0AD50, 0x05B52, 0x04B60, 0x0A6E6, 0x0A4E0, 0x0D260, 0x0EA65, 0x0D530, 0x05AA0, 0x076A3,
  61. 0x096D0, 0x04BD7, 0x04AD0, 0x0A4D0, 0x1D0B6, 0x0D250, 0x0D520, 0x0DD45, 0x0B5A0, 0x056D0, 0x055B2,
  62. 0x049B0, 0x0A577, 0x0A4B0, 0x0AA50, 0x1B255, 0x06D20, 0x0ADA0, 0x14B63, 0x9370, 0x49f8, 0x4970,
  63. 0x64b0, 0x168a6, 0xea50, 0x6aa0, 0x1a6c4, 0xaae0, 0x92e0, 0xd2e3, 0xc960, 0xd557, 0xd4a0, 0xda50,
  64. 0x5d55, 0x56a0, 0xa6d0, 0x55d4, 0x52d0, 0xa9b8, 0xa950, 0xb4a0, 0xb6a6, 0xad50, 0x55a0, 0xaba4,
  65. 0xa5b0, 0x52b0, 0xb273, 0x6930, 0x7337, 0x6aa0, 0xad50, 0x14b55, 0x4b60, 0xa570, 0x54e4, 0xd160,
  66. 0xe968, 0xd520, 0xdaa0, 0x16aa6, 0x56d0, 0x4ae0, 0xa9d4, 0xa2d0, 0xd150, 0xf252, 0xd520
  67. };
  68. /// <summary>
  69. /// 星座
  70. /// </summary>
  71. private static readonly string[] ConstellationName =
  72. {
  73. "白羊座", "金牛座", "双子座", "巨蟹座",
  74. "狮子座", "处女座", "天秤座", "天蝎座",
  75. "射手座", "摩羯座", "水瓶座", "双鱼座"
  76. };
  77. /// <summary>
  78. /// 二十八星宿
  79. /// </summary>
  80. private static readonly string[] ChineseConstellationName =
  81. {
  82. //四 五 六 日 一 二 三
  83. "角木蛟", "亢金龙","氐土貉" , "房日兔", "心月狐", "尾火虎", "箕水豹",
  84. "斗木獬", "牛金牛", "女土蝠", "虚日鼠", "危月燕", "室火猪", "壁水獝",
  85. "奎木狼", "娄金狗", "胃土彘", "昴日鸡", "毕月乌", "觜火猴", "参水猿",
  86. "井木犴", "鬼金羊", "柳土獐", "星日马", "张月鹿", "翼火蛇", "轸水蚓"
  87. };
  88. #region 节气数据
  89. /// <summary>
  90. /// 节气数据
  91. /// </summary>
  92. private static readonly string[] SolarTerm =
  93. {
  94. "小寒", "大寒", "立春", "雨水", "惊蛰", "春分",
  95. "清明", "谷雨", "立夏", "小满", "芒种", "夏至",
  96. "小暑", "大暑", "立秋", "处暑", "白露", "秋分",
  97. "寒露", "霜降", "立冬", "小雪", "大雪", "冬至"
  98. };
  99. private static readonly int[] STermInfo =
  100. {
  101. 0,
  102. 21208,
  103. 42467,
  104. 63836,
  105. 85337,
  106. 107014,
  107. 128867,
  108. 150921,
  109. 173149,
  110. 195551,
  111. 218072,
  112. 240693,
  113. 263343,
  114. 285989,
  115. 308563,
  116. 331033,
  117. 353350,
  118. 375494,
  119. 397447,
  120. 419210,
  121. 440795,
  122. 462224,
  123. 483532,
  124. 504758
  125. };
  126. #endregion 节气数据
  127. #region 农历相关数据
  128. private const string TianGan = "甲乙丙丁戊己庚辛壬癸";
  129. private const string DiZhi = "子丑寅卯辰巳午未申酉戌亥";
  130. private const string AnimalStr = "鼠牛虎兔龙蛇马羊猴鸡狗猪";
  131. private const string NStr1 = "日一二三四五六七八九";
  132. private const string NStr2 = "初十廿卅";
  133. private static readonly string[] MonthString =
  134. {
  135. "出错", "正月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "冬月", "腊月"
  136. };
  137. #endregion 农历相关数据
  138. #region 节日数据
  139. /// <summary>
  140. /// 自定义的工作日
  141. /// </summary>
  142. public static HashSet<DateTime> CustomWorkDays { get; } = [];
  143. /// <summary>
  144. /// 自定义的节假日
  145. /// </summary>
  146. public static Dictionary<DateTime, string> CustomHolidays { get; } = new();
  147. /// <summary>
  148. /// 按公历计算的通用节假日
  149. /// </summary>
  150. private static HashSet<DateInfoStruct> SolarHolidayInfo { get; } =
  151. [
  152. new DateInfoStruct(1, 1, 1, "元旦"),
  153. new DateInfoStruct(2, 2, 0, "世界湿地日"),
  154. new DateInfoStruct(2, 10, 0, "国际气象节"),
  155. new DateInfoStruct(2, 14, 0, "情人节"),
  156. new DateInfoStruct(3, 1, 0, "国际海豹日"),
  157. new DateInfoStruct(3, 5, 0, "学雷锋纪念日"),
  158. new DateInfoStruct(3, 8, 0, "妇女节"),
  159. new DateInfoStruct(3, 12, 0, "植树节 孙中山逝世纪念日"),
  160. new DateInfoStruct(3, 14, 0, "国际警察日"),
  161. new DateInfoStruct(3, 15, 0, "消费者权益日"),
  162. new DateInfoStruct(3, 17, 0, "中国国医节 国际航海日"),
  163. new DateInfoStruct(3, 21, 0, "世界森林日 消除种族歧视国际日 世界儿歌日"),
  164. new DateInfoStruct(3, 22, 0, "世界水日"),
  165. new DateInfoStruct(3, 24, 0, "世界防治结核病日"),
  166. new DateInfoStruct(4, 1, 0, "愚人节"),
  167. new DateInfoStruct(4, 5, 1, "清明节"),
  168. new DateInfoStruct(4, 7, 0, "世界卫生日"),
  169. new DateInfoStruct(4, 22, 0, "世界地球日"),
  170. new DateInfoStruct(5, 1, 1, "劳动节"),
  171. new DateInfoStruct(5, 4, 0, "青年节"),
  172. new DateInfoStruct(5, 8, 0, "世界红十字日"),
  173. new DateInfoStruct(5, 12, 0, "国际护士节"),
  174. new DateInfoStruct(5, 31, 0, "世界无烟日"),
  175. new DateInfoStruct(6, 1, 0, "国际儿童节"),
  176. new DateInfoStruct(6, 5, 0, "世界环境保护日"),
  177. new DateInfoStruct(6, 26, 0, "国际禁毒日"),
  178. new DateInfoStruct(7, 1, 0, "建党节 香港回归纪念 世界建筑日"),
  179. new DateInfoStruct(7, 11, 0, "世界人口日"),
  180. new DateInfoStruct(8, 1, 0, "建军节"),
  181. new DateInfoStruct(8, 8, 0, "中国男子节 父亲节"),
  182. new DateInfoStruct(8, 15, 0, "抗日战争胜利纪念"),
  183. new DateInfoStruct(9, 9, 0, " 逝世纪念"),
  184. new DateInfoStruct(9, 10, 0, "教师节"),
  185. new DateInfoStruct(9, 18, 0, "九·一八事变纪念日"),
  186. new DateInfoStruct(9, 20, 0, "国际爱牙日"),
  187. new DateInfoStruct(9, 27, 0, "世界旅游日"),
  188. new DateInfoStruct(9, 28, 0, "孔子诞辰"),
  189. new DateInfoStruct(10, 1, 7, "国庆节 国际音乐日"),
  190. new DateInfoStruct(10, 24, 0, "联合国日"),
  191. new DateInfoStruct(11, 10, 0, "世界青年节"),
  192. new DateInfoStruct(11, 12, 0, "孙中山诞辰纪念"),
  193. new DateInfoStruct(12, 1, 0, "世界艾滋病日"),
  194. new DateInfoStruct(12, 3, 0, "世界残疾人日"),
  195. new DateInfoStruct(12, 20, 0, "澳门回归纪念"),
  196. new DateInfoStruct(12, 24, 0, "平安夜"),
  197. new DateInfoStruct(12, 25, 0, "圣诞节"),
  198. new DateInfoStruct(12, 26, 0, " 诞辰纪念")
  199. ];
  200. /// <summary>
  201. /// 按农历计算的通用节假日
  202. /// </summary>
  203. private static HashSet<DateInfoStruct> LunarHolidayInfo { get; } =
  204. [
  205. new DateInfoStruct(1, 1, 6, "春节"),
  206. new DateInfoStruct(1, 15, 0, "元宵节"),
  207. new DateInfoStruct(5, 5, 1, "端午节"),
  208. new DateInfoStruct(7, 7, 0, "七夕情人节"),
  209. new DateInfoStruct(7, 15, 0, "中元节 盂兰盆节"),
  210. new DateInfoStruct(8, 15, 1, "中秋节"),
  211. new DateInfoStruct(9, 9, 0, "重阳节"),
  212. new DateInfoStruct(12, 8, 0, "腊八节"),
  213. new DateInfoStruct(12, 23, 0, "北方小年(扫房)"),
  214. new DateInfoStruct(12, 24, 0, "南方小年(掸尘)")
  215. //new HolidayStruct(12, 30, 0, "除夕") //注意除夕需要其它方法进行计算
  216. ];
  217. private static readonly WeekHolidayStruct[] WHolidayInfo =
  218. {
  219. new(5, 2, 1, "母亲节"),
  220. new(5, 3, 1, "全国助残日"),
  221. new(6, 3, 1, "父亲节"),
  222. new(9, 3, 3, "国际和平日"),
  223. new(9, 4, 1, "国际聋人节"),
  224. new(10, 1, 2, "国际住房日"),
  225. new(10, 1, 4, "国际减轻自然灾害日"),
  226. new(11, 4, 5, "感恩节")
  227. };
  228. #endregion 节日数据
  229. #endregion 基础数据
  230. /// <summary>
  231. /// 用一个标准的公历日期来初使化
  232. /// </summary>
  233. /// <param name="dt"></param>
  234. public ChineseCalendar(in DateTime dt)
  235. {
  236. if (dt.Year > MaxYear)
  237. {
  238. throw new ChineseCalendarException("最大年份支持2100年");
  239. }
  240. int i;
  241. Date = dt.Date;
  242. _datetime = dt;
  243. //农历日期计算部分
  244. var temp = 0;
  245. var ts = Date - MinDay; //计算两天的基本差距
  246. var offset = ts.Days;
  247. for (i = MinYear; i <= MaxYear; i++)
  248. {
  249. temp = GetChineseYearDays(i); //求当年农历年天数
  250. if (offset - temp < 1)
  251. {
  252. break;
  253. }
  254. offset = offset - temp;
  255. }
  256. ChineseYear = i;
  257. var leap = GetChineseLeapMonth(ChineseYear);
  258. //设定当年是否有闰月
  259. IsChineseLeapYear = leap > 0;
  260. IsChineseLeapMonth = false;
  261. for (i = 1; i <= 12; i++)
  262. {
  263. //闰月
  264. if (leap > 0 && i == leap + 1 && IsChineseLeapMonth == false)
  265. {
  266. IsChineseLeapMonth = true;
  267. i = i - 1;
  268. temp = GetChineseLeapMonthDays(ChineseYear); //计算闰月天数
  269. }
  270. else
  271. {
  272. IsChineseLeapMonth = false;
  273. temp = GetChineseMonthDays(ChineseYear, i); //计算非闰月天数
  274. }
  275. offset = offset - temp;
  276. if (offset <= 0)
  277. {
  278. break;
  279. }
  280. }
  281. offset = offset + temp;
  282. ChineseMonth = i;
  283. ChineseDay = offset;
  284. }
  285. /// <summary>
  286. /// 用农历的日期来初使化
  287. /// </summary>
  288. /// <param name="cy">农历年</param>
  289. /// <param name="cm">农历月</param>
  290. /// <param name="cd">农历日</param>
  291. /// <param name="leapMonthFlag">闰月标志</param>
  292. public ChineseCalendar(int cy, int cm, int cd, bool leapMonthFlag)
  293. {
  294. int i, temp;
  295. CheckChineseDateLimit(cy, cm, cd, leapMonthFlag);
  296. ChineseYear = cy;
  297. ChineseMonth = cm;
  298. ChineseDay = cd;
  299. var offset = 0;
  300. for (i = MinYear; i < cy; i++)
  301. {
  302. temp = GetChineseYearDays(i); //求当年农历年天数
  303. offset = offset + temp;
  304. }
  305. var leap = GetChineseLeapMonth(cy);
  306. IsChineseLeapYear = leap != 0;
  307. IsChineseLeapMonth = cm == leap && leapMonthFlag;
  308. if (IsChineseLeapYear == false || cm < leap) //当年没有闰月||计算月份小于闰月
  309. {
  310. for (i = 1; i < cm; i++)
  311. {
  312. temp = GetChineseMonthDays(cy, i); //计算非闰月天数
  313. offset = offset + temp;
  314. }
  315. //检查日期是否大于最大天
  316. if (cd > GetChineseMonthDays(cy, cm))
  317. {
  318. throw new ChineseCalendarException("不合法的农历日期");
  319. }
  320. offset = offset + cd; //加上当月的天数
  321. }
  322. else //是闰年,且计算月份大于或等于闰月
  323. {
  324. for (i = 1; i < cm; i++)
  325. {
  326. temp = GetChineseMonthDays(cy, i); //计算非闰月天数
  327. offset = offset + temp;
  328. }
  329. if (cm > leap) //计算月大于闰月
  330. {
  331. temp = GetChineseLeapMonthDays(cy); //计算闰月天数
  332. offset = offset + temp; //加上闰月天数
  333. if (cd > GetChineseMonthDays(cy, cm))
  334. {
  335. throw new ChineseCalendarException("不合法的农历日期");
  336. }
  337. offset = offset + cd;
  338. }
  339. else //计算月等于闰月
  340. {
  341. //如果需要计算的是闰月,则应首先加上与闰月对应的普通月的天数
  342. if (IsChineseLeapMonth) //计算月为闰月
  343. {
  344. temp = GetChineseMonthDays(cy, cm); //计算非闰月天数
  345. offset = offset + temp;
  346. }
  347. if (cd > GetChineseLeapMonthDays(cy))
  348. {
  349. throw new ChineseCalendarException("不合法的农历日期");
  350. }
  351. offset = offset + cd;
  352. }
  353. }
  354. Date = MinDay.AddDays(offset);
  355. }
  356. #region 私有函数
  357. /// <summary>
  358. /// 传回农历 y年m月的总天数
  359. /// </summary>
  360. /// <param name="year"></param>
  361. /// <param name="month"></param>
  362. /// <returns></returns>
  363. private int GetChineseMonthDays(int year, int month)
  364. {
  365. return BitTest32(LunarDateArray[year - MinYear] & 0x0000FFFF, 16 - month) ? 30 : 29;
  366. }
  367. /// <summary>
  368. /// 传回农历 y年闰哪个月 1-12 , 没闰传回 0
  369. /// </summary>
  370. /// <param name="year"></param>
  371. /// <returns></returns>
  372. private int GetChineseLeapMonth(int year)
  373. {
  374. return LunarDateArray[year - MinYear] & 0xF;
  375. }
  376. /// <summary>
  377. /// 传回农历 y年闰月的天数
  378. /// </summary>
  379. /// <param name="year"></param>
  380. /// <returns></returns>
  381. private int GetChineseLeapMonthDays(int year)
  382. {
  383. return GetChineseLeapMonth(year) != 0 ? (LunarDateArray[year - MinYear] & 0x10000) != 0 ? 30 : 29 : 0;
  384. }
  385. /// <summary>
  386. /// 取农历年一年的天数
  387. /// </summary>
  388. /// <param name="year"></param>
  389. /// <returns></returns>
  390. private int GetChineseYearDays(int year)
  391. {
  392. var sumDay = 348;
  393. var i = 0x8000;
  394. var info = LunarDateArray[year - MinYear] & 0x0FFFF;
  395. //计算12个月中有多少天为30天
  396. for (int m = 0; m < 12; m++)
  397. {
  398. var f = info & i;
  399. if (f != 0)
  400. {
  401. sumDay++;
  402. }
  403. i >>= 1;
  404. }
  405. return sumDay + GetChineseLeapMonthDays(year);
  406. }
  407. /// <summary>
  408. /// 获得当前时间的时辰
  409. /// </summary>
  410. /// <param name="dt"></param>
  411. /// <returns></returns>
  412. ///
  413. private string GetChineseHour(DateTime dt)
  414. {
  415. //计算时辰的地支
  416. var hour = dt.Hour;
  417. var minute = dt.Minute;
  418. if (minute != 0)
  419. {
  420. hour += 1;
  421. }
  422. var offset = hour / 2;
  423. if (offset >= 12)
  424. {
  425. offset = 0;
  426. }
  427. //计算天干
  428. var ts = Date - GanZhiStartDay;
  429. var i = ts.Days % 60;
  430. var indexGan = ((i % 10 + 1) * 2 - 1) % 10 - 1;
  431. var tmpGan = TianGan.Substring(indexGan) + TianGan.Substring(0, indexGan + 2);
  432. return tmpGan[offset].ToString() + DiZhi[offset];
  433. }
  434. /// <summary>
  435. /// 检查农历日期是否合理
  436. /// </summary>
  437. /// <param name="year"></param>
  438. /// <param name="month"></param>
  439. /// <param name="day"></param>
  440. /// <param name="leapMonth"></param>
  441. private void CheckChineseDateLimit(int year, int month, int day, bool leapMonth)
  442. {
  443. if (year < MinYear || year > MaxYear)
  444. {
  445. throw new ChineseCalendarException("非法农历日期");
  446. }
  447. if (month < 1 || month > 12)
  448. {
  449. throw new ChineseCalendarException("非法农历日期");
  450. }
  451. if (day is < 1 or > 30) //中国的月最多30天
  452. {
  453. throw new ChineseCalendarException("非法农历日期");
  454. }
  455. int leap = GetChineseLeapMonth(year); // 计算该年应该闰哪个月
  456. if (leapMonth && month != leap)
  457. {
  458. throw new ChineseCalendarException("非法农历日期");
  459. }
  460. }
  461. /// <summary>
  462. /// 将0-9转成汉字形式
  463. /// </summary>
  464. /// <param name="n"></param>
  465. /// <returns></returns>
  466. private string ConvertNumToChineseNum(char n)
  467. {
  468. if (n < '0' || n > '9')
  469. {
  470. return default;
  471. }
  472. return n switch
  473. {
  474. '0' => HzNum[0].ToString(),
  475. '1' => HzNum[1].ToString(),
  476. '2' => HzNum[2].ToString(),
  477. '3' => HzNum[3].ToString(),
  478. '4' => HzNum[4].ToString(),
  479. '5' => HzNum[5].ToString(),
  480. '6' => HzNum[6].ToString(),
  481. '7' => HzNum[7].ToString(),
  482. '8' => HzNum[8].ToString(),
  483. '9' => HzNum[9].ToString(),
  484. _ => default
  485. };
  486. }
  487. /// <summary>
  488. /// 测试某位是否为真
  489. /// </summary>
  490. /// <param name="num"></param>
  491. /// <param name="bitpostion"></param>
  492. /// <returns></returns>
  493. private bool BitTest32(int num, int bitpostion)
  494. {
  495. if (bitpostion > 31 || bitpostion < 0)
  496. {
  497. throw new ArgumentException("参数错误: 取值范围0-31", nameof(bitpostion));
  498. }
  499. int bit = 1 << bitpostion;
  500. return (num & bit) != 0;
  501. }
  502. /// <summary>
  503. /// 将星期几转成数字表示
  504. /// </summary>
  505. /// <param name="dayOfWeek"></param>
  506. /// <returns></returns>
  507. private int ConvertDayOfWeek(DayOfWeek dayOfWeek)
  508. {
  509. return dayOfWeek switch
  510. {
  511. DayOfWeek.Sunday => 1,
  512. DayOfWeek.Monday => 2,
  513. DayOfWeek.Tuesday => 3,
  514. DayOfWeek.Wednesday => 4,
  515. DayOfWeek.Thursday => 5,
  516. DayOfWeek.Friday => 6,
  517. DayOfWeek.Saturday => 7,
  518. _ => 0
  519. };
  520. }
  521. /// <summary>
  522. /// 比较当天是不是指定的第周几
  523. /// </summary>
  524. /// <param name="date"></param>
  525. /// <param name="month"></param>
  526. /// <param name="week"></param>
  527. /// <param name="day"></param>
  528. /// <returns></returns>
  529. private bool CompareWeekDayHoliday(DateTime date, int month, int week, int day)
  530. {
  531. bool result = false;
  532. if (date.Month == month) //月份相同
  533. {
  534. if (ConvertDayOfWeek(date.DayOfWeek) == day) //星期几相同
  535. {
  536. DateTime firstDay = new DateTime(date.Year, date.Month, 1); //生成当月第一天
  537. int i = ConvertDayOfWeek(firstDay.DayOfWeek);
  538. int firWeekDays = 7 - ConvertDayOfWeek(firstDay.DayOfWeek) + 1; //计算第一周剩余天数
  539. if (i > day)
  540. {
  541. if ((week - 1) * 7 + day + firWeekDays == date.Day)
  542. {
  543. result = true;
  544. }
  545. }
  546. else
  547. {
  548. if (day + firWeekDays + (week - 2) * 7 == date.Day)
  549. {
  550. result = true;
  551. }
  552. }
  553. }
  554. }
  555. return result;
  556. }
  557. #endregion 私有函数
  558. #region 节日
  559. /// <summary>
  560. /// 计算中国农历节日
  561. /// </summary>
  562. public string ChineseCalendarHoliday
  563. {
  564. get
  565. {
  566. string tempStr = "";
  567. if (IsChineseLeapMonth)
  568. {
  569. return tempStr;
  570. }
  571. foreach (var date in LunarHolidayInfo)
  572. {
  573. var end = date.Recess > 0 ? date.Day + date.Recess - 1 : date.Day + date.Recess;
  574. if (date.Month != ChineseMonth || ChineseDay < date.Day || ChineseDay > end)
  575. {
  576. continue;
  577. }
  578. tempStr = date.HolidayName;
  579. break;
  580. }
  581. //对除夕进行特别处理
  582. if (ChineseMonth != 12)
  583. {
  584. return tempStr;
  585. }
  586. int i = GetChineseMonthDays(ChineseYear, 12); //计算当年农历12月的总天数
  587. if (ChineseDay == i) //如果为最后一天
  588. {
  589. tempStr = "除夕";
  590. }
  591. return tempStr;
  592. }
  593. }
  594. /// <summary>
  595. /// 按某月第几周第几日计算的节日
  596. /// </summary>
  597. public string WeekDayHoliday
  598. {
  599. get
  600. {
  601. string tempStr = "";
  602. foreach (var wh in WHolidayInfo)
  603. {
  604. if (!CompareWeekDayHoliday(Date, wh.Month, wh.WeekAtMonth, wh.WeekDay))
  605. {
  606. continue;
  607. }
  608. tempStr = wh.HolidayName;
  609. break;
  610. }
  611. return tempStr;
  612. }
  613. }
  614. /// <summary>
  615. /// 按公历日计算的节日
  616. /// </summary>
  617. public string DateHoliday
  618. {
  619. get
  620. {
  621. string tempStr = "";
  622. foreach (DateInfoStruct sh in SolarHolidayInfo)
  623. {
  624. var end = sh.Recess > 0 ? sh.Day + sh.Recess - 1 : sh.Day + sh.Recess;
  625. if ((sh.Month == Date.Month) && Date.Day >= sh.Day && Date.Day <= end)
  626. {
  627. tempStr = sh.HolidayName;
  628. break;
  629. }
  630. if (CustomHolidays.Keys.Any(d => d.Date == Date))
  631. {
  632. tempStr = CustomHolidays[Date];
  633. break;
  634. }
  635. }
  636. return tempStr;
  637. }
  638. }
  639. /// <summary>
  640. /// 今天是否是假期
  641. /// </summary>
  642. public bool IsHoliday => !IsWorkDay;
  643. /// <summary>
  644. /// 今天是否是工作日
  645. /// </summary>
  646. public bool IsWorkDay
  647. {
  648. get
  649. {
  650. bool isHoliday = false;
  651. foreach (var date in SolarHolidayInfo)
  652. {
  653. var end = date.Recess > 0 ? date.Day + date.Recess - 1 : date.Day + date.Recess;
  654. if ((date.Month == Date.Month) && Date.Day >= date.Day && Date.Day <= end && date.Recess > 0)
  655. {
  656. isHoliday = true;
  657. break;
  658. }
  659. if (CustomHolidays.Keys.Any(d => d.Date == Date))
  660. {
  661. isHoliday = true;
  662. break;
  663. }
  664. }
  665. if (!isHoliday)
  666. {
  667. foreach (DateInfoStruct lh in LunarHolidayInfo)
  668. {
  669. var end = lh.Recess > 0 ? lh.Day + lh.Recess - 1 : lh.Day + lh.Recess;
  670. if (lh.Month == ChineseMonth && ChineseDay >= lh.Day && ChineseDay <= end && lh.Recess > 0)
  671. {
  672. isHoliday = true;
  673. break;
  674. }
  675. }
  676. //对除夕进行特别处理
  677. if (ChineseMonth == 12)
  678. {
  679. int i = GetChineseMonthDays(ChineseYear, 12); //计算当年农历12月的总天数
  680. if (ChineseDay == i) //如果为最后一天
  681. {
  682. isHoliday = true;
  683. }
  684. }
  685. }
  686. return !isHoliday && !IsWeekend() || CustomWorkDays.Any(s => s.Date == Date);
  687. }
  688. }
  689. /// <summary>
  690. /// 是否是周末
  691. /// </summary>
  692. /// <returns></returns>
  693. private bool IsWeekend()
  694. {
  695. return Date.DayOfWeek == DayOfWeek.Saturday || Date.DayOfWeek == DayOfWeek.Sunday;
  696. }
  697. #endregion 节日
  698. #region 公历日期
  699. /// <summary>
  700. /// 取对应的公历日期
  701. /// </summary>
  702. public DateTime Date { get; set; }
  703. /// <summary>
  704. /// 取星期几
  705. /// </summary>
  706. public DayOfWeek WeekDay => Date.DayOfWeek;
  707. /// <summary>
  708. /// 周几的字符
  709. /// </summary>
  710. public string WeekDayStr => Date.DayOfWeek switch
  711. {
  712. DayOfWeek.Sunday => "星期日",
  713. DayOfWeek.Monday => "星期一",
  714. DayOfWeek.Tuesday => "星期二",
  715. DayOfWeek.Wednesday => "星期三",
  716. DayOfWeek.Thursday => "星期四",
  717. DayOfWeek.Friday => "星期五",
  718. _ => "星期六"
  719. };
  720. /// <summary>
  721. /// 公历日期中文表示法 如一九九七年七月一日
  722. /// </summary>
  723. public string DateString => "公元" + Date.ToLongDateString();
  724. /// <summary>
  725. /// 当前是否公历闰年
  726. /// </summary>
  727. public bool IsLeapYear => DateTime.IsLeapYear(Date.Year);
  728. /// <summary>
  729. /// 28星宿计算
  730. /// </summary>
  731. public string ChineseConstellation
  732. {
  733. get
  734. {
  735. var ts = Date - ChineseConstellationReferDay;
  736. var offset = ts.Days;
  737. var modStarDay = offset % 28;
  738. return (modStarDay >= 0 ? ChineseConstellationName[modStarDay] : ChineseConstellationName[27 + modStarDay]);
  739. }
  740. }
  741. /// <summary>
  742. /// 时辰
  743. /// </summary>
  744. public string ChineseHour => GetChineseHour(_datetime);
  745. #endregion 公历日期
  746. #region 农历日期
  747. /// <summary>
  748. /// 农历今天
  749. /// </summary>
  750. public static ChineseCalendar Today => new(DateTime.Today);
  751. /// <summary>
  752. /// 是否闰月
  753. /// </summary>
  754. public bool IsChineseLeapMonth { get; }
  755. /// <summary>
  756. /// 当年是否有闰月
  757. /// </summary>
  758. public bool IsChineseLeapYear { get; }
  759. /// <summary>
  760. /// 农历日
  761. /// </summary>
  762. public int ChineseDay { get; }
  763. /// <summary>
  764. /// 农历日中文表示
  765. /// </summary>
  766. public string ChineseDayString => ChineseDay switch
  767. {
  768. 0 => "",
  769. 10 => "初十",
  770. 20 => "二十",
  771. 30 => "三十",
  772. _ => (NStr2[ChineseDay / 10] + NStr1[ChineseDay % 10].ToString())
  773. };
  774. /// <summary>
  775. /// 农历的月份
  776. /// </summary>
  777. public int ChineseMonth { get; }
  778. /// <summary>
  779. /// 农历月份字符串
  780. /// </summary>
  781. public string ChineseMonthString => MonthString[ChineseMonth];
  782. /// <summary>
  783. /// 取农历年份
  784. /// </summary>
  785. public int ChineseYear { get; }
  786. /// <summary>
  787. /// 取农历年字符串如,一九九七年
  788. /// </summary>
  789. public string ChineseYearString
  790. {
  791. get
  792. {
  793. string tempStr = "";
  794. string num = ChineseYear.ToString();
  795. for (int i = 0; i < 4; i++)
  796. {
  797. tempStr += ConvertNumToChineseNum(num[i]);
  798. }
  799. return tempStr + "年";
  800. }
  801. }
  802. /// <summary>
  803. /// 取农历日期表示法:农历一九九七年正月初五
  804. /// </summary>
  805. public string ChineseDateString
  806. {
  807. get
  808. {
  809. if (IsChineseLeapMonth)
  810. {
  811. return ChineseYearString + "闰" + ChineseMonthString + ChineseDayString;
  812. }
  813. return ChineseYearString + ChineseMonthString + ChineseDayString;
  814. }
  815. }
  816. /// <summary>
  817. /// 定气法计算二十四节气,二十四节气是按地球公转来计算的,并非是阴历计算的
  818. /// </summary>
  819. /// <remarks>
  820. /// 节气的定法有两种。古代历法采用的称为"恒气",即按时间把一年等分为24份,
  821. /// 每一节气平均得15天有余,所以又称"平气"。现代农历采用的称为"定气",即
  822. /// 按地球在轨道上的位置为标准,一周360°,两节气之间相隔15°。由于冬至时地
  823. /// 球位于近日点附近,运动速度较快,因而太阳在黄道上移动15°的时间不到15天。
  824. /// 夏至前后的情况正好相反,太阳在黄道上移动较慢,一个节气达16天之多。采用
  825. /// 定气时可以保证春、秋两分必然在昼夜平分的那两天。
  826. /// </remarks>
  827. public string ChineseTwentyFourDay
  828. {
  829. get
  830. {
  831. var baseDateAndTime = new DateTime(1900, 1, 6, 2, 5, 0, DateTimeKind.Local); //#1/6/1900 2:05:00 AM#
  832. string tempStr = "";
  833. var y = Date.Year;
  834. for (int i = 1; i <= 24; i++)
  835. {
  836. var num = 525948.76 * (y - 1900) + STermInfo[i - 1];
  837. var newDate = baseDateAndTime.AddMinutes(num);
  838. if (newDate.DayOfYear != Date.DayOfYear)
  839. {
  840. continue;
  841. }
  842. tempStr = SolarTerm[i - 1];
  843. break;
  844. }
  845. return tempStr;
  846. }
  847. }
  848. /// <summary>
  849. /// 当前日期前一个最近节气
  850. /// </summary>
  851. public string ChineseTwentyFourPrevDay
  852. {
  853. get
  854. {
  855. DateTime baseDateAndTime = new DateTime(1900, 1, 6, 2, 5, 0, DateTimeKind.Local); //#1/6/1900 2:05:00 AM#
  856. string tempStr = "";
  857. var y = Date.Year;
  858. for (int i = 24; i >= 1; i--)
  859. {
  860. var num = 525948.76 * (y - 1900) + STermInfo[i - 1];
  861. var newDate = baseDateAndTime.AddMinutes(num);
  862. if (newDate.DayOfYear < Date.DayOfYear)
  863. {
  864. tempStr = $"{SolarTerm[i - 1]}[{newDate:yyyy-MM-dd}]";
  865. break;
  866. }
  867. }
  868. return tempStr;
  869. }
  870. }
  871. /// <summary>
  872. /// 当前日期后一个最近节气
  873. /// </summary>
  874. public string ChineseTwentyFourNextDay
  875. {
  876. get
  877. {
  878. var baseDateAndTime = new DateTime(1900, 1, 6, 2, 5, 0, DateTimeKind.Local); //#1/6/1900 2:05:00 AM#
  879. string tempStr = "";
  880. var y = Date.Year;
  881. for (int i = 1; i <= 24; i++)
  882. {
  883. var num = 525948.76 * (y - 1900) + STermInfo[i - 1];
  884. var newDate = baseDateAndTime.AddMinutes(num);
  885. if (newDate.DayOfYear > Date.DayOfYear)
  886. {
  887. tempStr = $"{SolarTerm[i - 1]}[{newDate:yyyy-MM-dd}]";
  888. break;
  889. }
  890. }
  891. return tempStr;
  892. }
  893. }
  894. #endregion 农历日期
  895. #region 星座
  896. /// <summary>
  897. /// 计算指定日期的星座序号
  898. /// </summary>
  899. /// <returns></returns>
  900. public string Constellation
  901. {
  902. get
  903. {
  904. int index;
  905. var m = Date.Month;
  906. var d = Date.Day;
  907. var y = m * 100 + d;
  908. if (y is >= 321 and <= 419)
  909. {
  910. index = 0;
  911. }
  912. else if (y is >= 420 and <= 520)
  913. {
  914. index = 1;
  915. }
  916. else if (y is >= 521 and <= 620)
  917. {
  918. index = 2;
  919. }
  920. else if (y is >= 621 and <= 722)
  921. {
  922. index = 3;
  923. }
  924. else if (y is >= 723 and <= 822)
  925. {
  926. index = 4;
  927. }
  928. else if (y is >= 823 and <= 922)
  929. {
  930. index = 5;
  931. }
  932. else if (y is >= 923 and <= 1022)
  933. {
  934. index = 6;
  935. }
  936. else if (y >= 1023 && y <= 1121)
  937. {
  938. index = 7;
  939. }
  940. else if (y is >= 1122 and <= 1221)
  941. {
  942. index = 8;
  943. }
  944. else if (y is >= 1222 or <= 119)
  945. {
  946. index = 9;
  947. }
  948. else if (y is >= 120 and <= 218)
  949. {
  950. index = 10;
  951. }
  952. else if (y is >= 219 and <= 320)
  953. {
  954. index = 11;
  955. }
  956. else
  957. {
  958. index = 0;
  959. }
  960. return ConstellationName[index];
  961. }
  962. }
  963. #endregion 星座
  964. #region 生肖
  965. /// <summary>
  966. /// 计算属相的索引,注意虽然属相是以农历年来区别的,但是目前在实际使用中是按公历来计算的
  967. /// 鼠年为1,其它类推
  968. /// </summary>
  969. public int Animal
  970. {
  971. get
  972. {
  973. int offset = Date.Year - AnimalStartYear;
  974. return offset % 12 + 1;
  975. }
  976. }
  977. /// <summary>
  978. /// 取属相字符串
  979. /// </summary>
  980. public string AnimalString
  981. {
  982. get
  983. {
  984. int offset = Date.Year - AnimalStartYear; //阳历计算
  985. return AnimalStr[offset % 12].ToString();
  986. }
  987. }
  988. #endregion 生肖
  989. #region 天干地支
  990. /// <summary>
  991. /// 取农历年的干支表示法如 乙丑年
  992. /// </summary>
  993. public string GanZhiYearString
  994. {
  995. get
  996. {
  997. int i = (ChineseYear - GanZhiStartYear) % 60; //计算干支
  998. var tempStr = TianGan[i % 10] + DiZhi[i % 12].ToString() + "年";
  999. return tempStr;
  1000. }
  1001. }
  1002. /// <summary>
  1003. /// 取干支的月表示字符串,注意农历的闰月不记干支
  1004. /// </summary>
  1005. public string GanZhiMonthString
  1006. {
  1007. get
  1008. {
  1009. //每个月的地支总是固定的,而且总是从寅月开始
  1010. int zhiIndex;
  1011. if (ChineseMonth > 10)
  1012. {
  1013. zhiIndex = ChineseMonth - 10;
  1014. }
  1015. else
  1016. {
  1017. zhiIndex = ChineseMonth + 2;
  1018. }
  1019. var zhi = DiZhi[zhiIndex - 1].ToString();
  1020. //根据当年的干支年的干来计算月干的第一个
  1021. int ganIndex = 1;
  1022. int i = (ChineseYear - GanZhiStartYear) % 60; //计算干支
  1023. ganIndex = (i % 10) switch
  1024. {
  1025. 0 => 3, //甲
  1026. 1 => 5, //乙
  1027. 2 => 7, //丙
  1028. 3 => 9, //丁
  1029. 4 => 1, //戊
  1030. 5 => 3, //己
  1031. 6 => 5, //庚
  1032. 7 => 7, //辛
  1033. 8 => 9, //壬
  1034. 9 => 1, //癸
  1035. _ => ganIndex
  1036. };
  1037. var gan = TianGan[(ganIndex + ChineseMonth - 2) % 10].ToString();
  1038. return gan + zhi + "月";
  1039. }
  1040. }
  1041. /// <summary>
  1042. /// 取干支日表示法
  1043. /// </summary>
  1044. public string GanZhiDayString
  1045. {
  1046. get
  1047. {
  1048. var ts = Date - GanZhiStartDay;
  1049. var offset = ts.Days;
  1050. var i = offset % 60;
  1051. return TianGan[i % 10].ToString() + DiZhi[i % 12] + "日";
  1052. }
  1053. }
  1054. /// <summary>
  1055. /// 取当前日期的干支表示法如 甲子年乙丑月丙庚日
  1056. /// </summary>
  1057. public string GanZhiDateString => GanZhiYearString + GanZhiMonthString + GanZhiDayString;
  1058. #endregion 天干地支
  1059. /// <summary>
  1060. /// 取下一天
  1061. /// </summary>
  1062. /// <returns></returns>
  1063. public ChineseCalendar NextDay => new(Date.AddDays(1));
  1064. /// <summary>
  1065. /// 取前一天
  1066. /// </summary>
  1067. /// <returns></returns>
  1068. public ChineseCalendar PervDay => new(Date.AddDays(-1));
  1069. /// <summary>
  1070. /// 取下n天
  1071. /// </summary>
  1072. /// <returns></returns>
  1073. public ChineseCalendar AddDays(int days)
  1074. {
  1075. return new ChineseCalendar(Date.AddDays(days));
  1076. }
  1077. /// <summary>
  1078. /// 取下n天
  1079. /// </summary>
  1080. /// <returns></returns>
  1081. public ChineseCalendar AddWorkDays(int days)
  1082. {
  1083. var cc = new ChineseCalendar(Date);
  1084. while (true)
  1085. {
  1086. cc = cc.AddDays(1);
  1087. if (cc.IsWorkDay)
  1088. {
  1089. days--;
  1090. }
  1091. if (days == 0)
  1092. {
  1093. return cc;
  1094. }
  1095. }
  1096. }
  1097. /// <summary>
  1098. /// 加n月
  1099. /// </summary>
  1100. /// <returns></returns>
  1101. public ChineseCalendar AddMonths(int months)
  1102. {
  1103. return new ChineseCalendar(Date.AddMonths(months));
  1104. }
  1105. }
  1106. }