params关键字、工具辅助类与、加密与解密
一、params关键字
在C#中如果给方法的参数加上关键字params则会形成可变参数,在传递时可以是0-n个对象。
示例:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms; namespace Chapter6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void Form1_Load(object sender, EventArgs e)
{
Console.WriteLine(add(add(,),));
Console.WriteLine(addPro(new int[]{,,,,,}));
Console.WriteLine(addSuperPro());
Console.WriteLine(addSuperPro(,));
Console.WriteLine(addSuperPro(, ,,,,,));
Console.WriteLine(addSuperPro());
} public int add(int n1, int n2)
{
return n1 + n2;
} public int addPro(int[] n1)
{
int result = ;
foreach (var item in n1)
{
result += item;
}
return result;
} /// <summary>
/// 实现多个数相加
/// </summary>
/// <param name="n0">带默认值的方法参数</param>
/// <param name="n1">可变化的参数,可以指定0-n个int类型的值</param>
/// <returns>和</returns>
public int addSuperPro(int n0=,params int[] n1)
{
int result = ;
foreach (int item in n1)
{
result += item;
}
return result;
}
}
}
结果:
注意:
params只允许修饰方法中的数组类型参数
parmas只能出现一次,且必须是最后一个参数
二、工具(辅助)类
工具类有人也称辅助类,主要是一些用于完成特定功能的方法,可以在多个项目中反复使用,好处是可以提高开发效率与质量。
项目中常用要用到MessageBox.Show方法且可能被变化,则可以封装成一个静态方法:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using System.Windows.Forms; namespace Chapter6
{
public class MsgUtils
{
public static void Show(String msg)
{
MessageBox.Show(msg+DateTime.Now);
System.IO.File.AppendAllText("c:/log.txt",msg);
}
}
}
调用:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms; namespace Chapter6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void Form1_Load(object sender, EventArgs e)
{
Console.WriteLine(add(add(,),));
Console.WriteLine(addPro(new int[]{,,,,,}));
Console.WriteLine(addSuperPro());
Console.WriteLine(addSuperPro(,));
Console.WriteLine(addSuperPro(, ,,,,,));
Console.WriteLine(addSuperPro());
} public int add(int n1, int n2)
{
return n1 + n2;
} public int addPro(int[] n1)
{
int result = ;
foreach (var item in n1)
{
result += item;
}
return result;
} /// <summary>
/// 实现多个数相加
/// </summary>
/// <param name="n0">带默认值的方法参数</param>
/// <param name="n1">可变化的参数,可以指定0-n个int类型的值</param>
/// <returns>和</returns>
public int addSuperPro(int n0=,params int[] n1)
{
int result = ;
foreach (int item in n1)
{
result += item;
}
return result;
} private void button1_Click(object sender, EventArgs e)
{
MsgUtils.Show("Hello1");
} private void button2_Click(object sender, EventArgs e)
{
MsgUtils.Show("Hello2");
} private void button3_Click(object sender, EventArgs e)
{
MsgUtils.Show("Hello3");
}
}
}
好处是:当MsgUtils.Show变化时则整个项目中的所有引用都变化,被管理,被封装。
假定我现在要实现公历与农历的转换:
示例:
CNDate工具类:
using System; namespace Chapter6
{
/// <summary>
/// 农历属性
/// </summary>
public class CNDate
{
/// <summary>
/// 农历年(整型)
/// </summary>
public int cnIntYear = ;
/// <summary>
/// 农历月份(整型)
/// </summary>
public int cnIntMonth = ;
/// <summary>
/// 农历天(整型)
/// </summary>
public int cnIntDay = ;
/// <summary>
/// 农历年(支干)
/// </summary>
public string cnStrYear = "";
/// <summary>
/// 农历月份(字符)
/// </summary>
public string cnStrMonth = "";
/// <summary>
/// 农历天(字符)
/// </summary>
public string cnStrDay = "";
/// <summary>
/// 农历属象
/// </summary>
public string cnAnm = "";
/// <summary>
/// 二十四节气
/// </summary>
public string cnSolarTerm = "";
/// <summary>
/// 阴历节日
/// </summary>
public string cnFtvl = "";
/// <summary>
/// 阳历节日
/// </summary>
public string cnFtvs = "";
} /// <summary>
/// 公历转农历
/// </summary>
public class ChinaDate
{
#region 私有方法
private static long[] lunarInfo = new long[] { 0x04bd8, 0x04ae0, 0x0a570, 0x054d5, 0x0d260, 0x0d950, 0x16554,
0x056a0, 0x09ad0, 0x055d2, 0x04ae0, 0x0a5b6, 0x0a4d0, 0x0d250, 0x1d255, 0x0b540, 0x0d6a0, 0x0ada2, 0x095b0,
0x14977, 0x04970, 0x0a4b0, 0x0b4b5, 0x06a50, 0x06d40, 0x1ab54, 0x02b60, 0x09570, 0x052f2, 0x04970, 0x06566,
0x0d4a0, 0x0ea50, 0x06e95, 0x05ad0, 0x02b60, 0x186e3, 0x092e0, 0x1c8d7, 0x0c950, 0x0d4a0, 0x1d8a6, 0x0b550,
0x056a0, 0x1a5b4, 0x025d0, 0x092d0, 0x0d2b2, 0x0a950, 0x0b557, 0x06ca0, 0x0b550, 0x15355, 0x04da0, 0x0a5d0,
0x14573, 0x052d0, 0x0a9a8, 0x0e950, 0x06aa0, 0x0aea6, 0x0ab50, 0x04b60, 0x0aae4, 0x0a570, 0x05260, 0x0f263,
0x0d950, 0x05b57, 0x056a0, 0x096d0, 0x04dd5, 0x04ad0, 0x0a4d0, 0x0d4d4, 0x0d250, 0x0d558, 0x0b540, 0x0b5a0,
0x195a6, 0x095b0, 0x049b0, 0x0a974, 0x0a4b0, 0x0b27a, 0x06a50, 0x06d40, 0x0af46, 0x0ab60, 0x09570, 0x04af5,
0x04970, 0x064b0, 0x074a3, 0x0ea50, 0x06b58, 0x055c0, 0x0ab60, 0x096d5, 0x092e0, 0x0c960, 0x0d954, 0x0d4a0,
0x0da50, 0x07552, 0x056a0, 0x0abb7, 0x025d0, 0x092d0, 0x0cab5, 0x0a950, 0x0b4a0, 0x0baa4, 0x0ad50, 0x055d9,
0x04ba0, 0x0a5b0, 0x15176, 0x052b0, 0x0a930, 0x07954, 0x06aa0, 0x0ad50, 0x05b52, 0x04b60, 0x0a6e6, 0x0a4e0,
0x0d260, 0x0ea65, 0x0d530, 0x05aa0, 0x076a3, 0x096d0, 0x04bd7, 0x04ad0, 0x0a4d0, 0x1d0b6, 0x0d250, 0x0d520,
0x0dd45, 0x0b5a0, 0x056d0, 0x055b2, 0x049b0, 0x0a577, 0x0a4b0, 0x0aa50, 0x1b255, 0x06d20, 0x0ada0 }; private static int[] year20 = new int[] { , , , , , , , , , , , };
private static int[] year19 = new int[] { , , , , , , , , , , , };
private static int[] year2000 = new int[] { , , , , , , , , , , , };
private static String[] nStr1 = new String[] { "", "正", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二" };
private static String[] Gan = new String[] { "甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸" };
private static String[] Zhi = new String[] { "子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥" };
private static String[] Animals = new String[] { "鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪" };
private static String[] solarTerm = new String[] { "小寒", "大寒", "立春", "雨水", "惊蛰", "春分", "清明", "谷雨", "立夏", "小满", "芒种", "夏至", "小暑", "大暑", "立秋", "处暑", "白露", "秋分", "寒露", "霜降", "立冬", "小雪", "大雪", "冬至" };
private static int[] sTermInfo = { , , , , , , , , , , , , , , , , , , , , , , , };
private static String[] lFtv = new String[] { "0101农历春节", "0202 龙抬头节", "0115 元宵节", "0505 端午节", "0707 七夕情人节", "0815 中秋节", "0909 重阳节", "1208 腊八节", "1114 李君先生生日", "1224 小年", "0100除夕" };
private static String[] sFtv = new String[] { "0101 新年元旦",
"0202 世界湿地日",
"0207 国际声援南非日",
"0210 国际气象节",
"0214 情人节",
"0301 国际海豹日",
"0303 全国爱耳日",
"0308 国际妇女节",
"0312 植树节 孙中山逝世纪念日",
"0314 国际警察日",
"0315 国际消费者权益日",
"0317 中国国医节 国际航海日",
"0321 世界森林日 消除种族歧视国际日",
"0321 世界儿歌日",
"0322 世界水日",
"0323 世界气象日",
"0324 世界防治结核病日",
"0325 全国中小学生安全教育日",
"0330 巴勒斯坦国土日",
"0401 愚人节 全国爱国卫生运动月(四月) 税收宣传月(四月)",
"0407 世界卫生日",
"0422 世界地球日",
"0423 世界图书和版权日",
"0424 亚非新闻工作者日",
"0501 国际劳动节",
"0504 中国五四青年节",
"0505 碘缺乏病防治日",
"0508 世界红十字日",
"0512 国际护士节",
"0515 国际家庭日",
"0517 世界电信日",
"0518 国际博物馆日",
"0520 全国学生营养日",
"0523 国际牛奶日",
"0531 世界无烟日",
"0601 国际儿童节",
"0605 世界环境日",
"0606 全国爱眼日",
"0617 防治荒漠化和干旱日",
"0623 国际奥林匹克日",
"0625 全国土地日",
"0626 国际反毒品日",
"0701 中国建党日 世界建筑日",
"0702 国际体育记者日",
"0707 中国人民抗日战争纪念日",
"0711 世界人口日",
"0730 非洲妇女日",
"0801 中国建军节",
"0808 中国男子节(爸爸节)",
"0815 日本正式宣布无条件投降日",
"0908 国际扫盲日 国际新闻工作者日",
"0910 教师节",
"0914 世界清洁地球日",
"0916 国际臭氧层保护日",
"0918 九·一八事变纪念日",
"0920 全国爱牙日",
"0927 世界旅游日",
"1001 国庆节 世界音乐日 国际老人节",
"1001 国际音乐日",
"1002 国际和平与民主自由斗争日",
"1004 世界动物日",
"1008 全国高血压日",
"1008 世界视觉日",
"1009 世界邮政日 万国邮联日",
"1010 辛亥革命纪念日 世界精神卫生日",
"1013 世界保健日 国际教师节",
"1014 世界标准日",
"1015 国际盲人节(白手杖节)",
"1016 世界粮食日",
"1017 世界消除贫困日",
"1022 世界传统医药日",
"1024 联合国日 世界发展信息日",
"1031 世界勤俭日",
"1107 十月社会主义革命纪念日",
"1108 中国记者日",
"1109 全国消防安全宣传教育日",
"1110 世界青年节",
"1111 国际科学与和平周(本日所属的一周)",
"1112 孙中山诞辰纪念日",
"1114 世界糖尿病日",
"1117 国际大学生节 世界学生节",
"1121 世界问候日 世界电视日",
"1129 国际声援巴勒斯坦人民国际日",
"1201 世界艾滋病日",
"1203 世界残疾人日",
"1205 国际经济和社会发展志愿人员日",
"1208 国际儿童电视日",
"1209 世界足球日",
"1210 世界人权日",
"1212 西安事变纪念日",
"1213 南京大屠杀(1937年)纪念日!紧记血泪史!",
"1221 国际篮球日",
"1224 平安夜",
"1225 圣诞节",
"1226 毛主席诞辰",
"1229 国际生物多样性日" }; /// <summary>
/// 传回农历y年的总天数
/// </summary>
private static int lYearDays(int y)
{
int i, sum = ;
for (i = 0x8000; i > 0x8; i >>= )
{
if ((lunarInfo[y - ] & i) != )
sum += ;
}
return (sum + leapDays(y));
} /// <summary>
/// 传回农历y年闰月的天数
/// </summary>
private static int leapDays(int y)
{
if (leapMonth(y) != )
{
if ((lunarInfo[y - ] & 0x10000) != )
return ;
else
return ;
}
else
return ;
} /// <summary>
/// 传回农历y年闰哪个月 1-12 , 没闰传回 0
/// </summary>
private static int leapMonth(int y)
{
return (int)(lunarInfo[y - ] & 0xf);
} /// <summary>
/// 传回农历y年m月的总天数
/// </summary>
private static int monthDays(int y, int m)
{
if ((lunarInfo[y - ] & (0x10000 >> m)) == )
return ;
else
return ;
} /// <summary>
/// 传回农历y年的生肖
/// </summary>
private static String AnimalsYear(int y)
{
return Animals[(y - ) % ];
} /// <summary>
/// 传入月日的offset 传回干支,0=甲子
/// </summary>
private static String cyclicalm(int num)
{
return (Gan[num % ] + Zhi[num % ]);
} /// <summary>
/// 传入offset 传回干支, 0=甲子
/// </summary>
private static String cyclical(int y)
{
int num = y - + ;
return (cyclicalm(num));
} /// <summary>
/// 传出农历.year0 .month1 .day2 .yearCyl3 .monCyl4 .dayCyl5 .isLeap6
/// </summary>
private long[] Lunar(int y, int m)
{
long[] nongDate = new long[];
int i = , temp = , leap = ;
DateTime baseDate = new DateTime( + , , );
DateTime objDate = new DateTime(y + , m + , );
TimeSpan ts = objDate - baseDate;
long offset = (long)ts.TotalDays;
if (y < )
offset += year19[m - ];
if (y > )
offset += year20[m - ];
if (y == )
offset += year2000[m - ];
nongDate[] = offset + ;
nongDate[] = ; for (i = ; i < && offset > ; i++)
{
temp = lYearDays(i);
offset -= temp;
nongDate[] += ;
}
if (offset < )
{
offset += temp;
i--;
nongDate[] -= ;
}
nongDate[] = i;
nongDate[] = i - ;
leap = leapMonth(i); // 闰哪个月
nongDate[] = ; for (i = ; i < && offset > ; i++)
{
// 闰月
if (leap > && i == (leap + ) && nongDate[] == )
{
--i;
nongDate[] = ;
temp = leapDays((int)nongDate[]);
}
else
{
temp = monthDays((int)nongDate[], i);
} // 解除闰月
if (nongDate[] == && i == (leap + ))
nongDate[] = ;
offset -= temp;
if (nongDate[] == )
nongDate[]++;
} if (offset == && leap > && i == leap + )
{
if (nongDate[] == )
{
nongDate[] = ;
}
else
{
nongDate[] = ;
--i;
--nongDate[];
}
}
if (offset < )
{
offset += temp;
--i;
--nongDate[];
}
nongDate[] = i;
nongDate[] = offset + ;
return nongDate;
} /// <summary>
/// 传出y年m月d日对应的农历.year0 .month1 .day2 .yearCyl3 .monCyl4 .dayCyl5 .isLeap6
/// </summary>
private static long[] calElement(int y, int m, int d)
{
long[] nongDate = new long[];
int i = , temp = , leap = ; DateTime baseDate = new DateTime(, , ); DateTime objDate = new DateTime(y, m, d);
TimeSpan ts = objDate - baseDate; long offset = (long)ts.TotalDays; nongDate[] = offset + ;
nongDate[] = ; for (i = ; i < && offset > ; i++)
{
temp = lYearDays(i);
offset -= temp;
nongDate[] += ;
}
if (offset < )
{
offset += temp;
i--;
nongDate[] -= ;
}
nongDate[] = i;
nongDate[] = i - ;
leap = leapMonth(i); // 闰哪个月
nongDate[] = ; for (i = ; i < && offset > ; i++)
{
// 闰月
if (leap > && i == (leap + ) && nongDate[] == )
{
--i;
nongDate[] = ;
temp = leapDays((int)nongDate[]);
}
else
{
temp = monthDays((int)nongDate[], i);
} // 解除闰月
if (nongDate[] == && i == (leap + ))
nongDate[] = ;
offset -= temp;
if (nongDate[] == )
nongDate[]++;
} if (offset == && leap > && i == leap + )
{
if (nongDate[] == )
{
nongDate[] = ;
}
else
{
nongDate[] = ;
--i;
--nongDate[];
}
}
if (offset < )
{
offset += temp;
--i;
--nongDate[];
}
nongDate[] = i;
nongDate[] = offset + ;
return nongDate;
} private static String getChinaDate(int day)
{
String a = "";
if (day == )
return "初十";
if (day == )
return "二十";
if (day == )
return "三十";
int two = (int)((day) / );
if (two == )
a = "初";
if (two == )
a = "十";
if (two == )
a = "廿";
if (two == )
a = "三";
int one = (int)(day % );
switch (one)
{
case :
a += "一";
break;
case :
a += "二";
break;
case :
a += "三";
break;
case :
a += "四";
break;
case :
a += "五";
break;
case :
a += "六";
break;
case :
a += "七";
break;
case :
a += "八";
break;
case :
a += "九";
break;
}
return a;
} private static DateTime sTerm(int y, int n)
{
double ms = 31556925974.7 * (y - );
double ms1 = sTermInfo[n];
DateTime offDate = new DateTime(, , , , , );
offDate = offDate.AddMilliseconds(ms);
offDate = offDate.AddMinutes(ms1);
return offDate;
} static string FormatDate(int m, int d)
{
return string.Format("{0:00}{1:00}", m, d);
}
#endregion #region 公有方法
/// <summary>
/// 传回公历y年m月的总天数
/// </summary>
public static int GetDaysByMonth(int y, int m)
{
int[] days = new int[] { , DateTime.IsLeapYear(y) ? : , , , , , , , , , , };
return days[m - ];
} /// <summary>
/// 根据日期值获得周一的日期
/// </summary>
/// <param name="dt">输入日期</param>
/// <returns>周一的日期</returns>
public static DateTime GetMondayDateByDate(DateTime dt)
{
double d = ;
switch ((int)dt.DayOfWeek)
{
//case 1: d = 0; break;
case : d = -; break;
case : d = -; break;
case : d = -; break;
case : d = -; break;
case : d = -; break;
case : d = -; break;
}
return dt.AddDays(d);
} /// <summary>
/// 获取农历
/// </summary>
public static CNDate getChinaDate(DateTime dt)
{
CNDate cd = new CNDate();
int year = dt.Year;
int month = dt.Month;
int date = dt.Day;
long[] l = calElement(year, month, date);
cd.cnIntYear = (int)l[];
cd.cnIntMonth = (int)l[];
cd.cnIntDay = (int)l[];
cd.cnStrYear = cyclical(year);
cd.cnAnm = AnimalsYear(year);
cd.cnStrMonth = nStr1[(int)l[]];
cd.cnStrDay = getChinaDate((int)(l[]));
string smd = dt.ToString("MMdd"); string lmd = FormatDate(cd.cnIntMonth, cd.cnIntDay);
for (int i = ; i < solarTerm.Length; i++)
{
string s1 = sTerm(dt.Year, i).ToString("MMdd");
if (s1.Equals(dt.ToString("MMdd")))
{
cd.cnSolarTerm = solarTerm[i];
break;
}
}
foreach (string s in sFtv)
{
string s1 = s.Substring(, );
if (s1.Equals(smd))
{
cd.cnFtvs = s.Substring(, s.Length - );
break;
}
}
foreach (string s in lFtv)
{
string s1 = s.Substring(, );
if (s1.Equals(lmd))
{
cd.cnFtvl = s.Substring(, s.Length - );
break;
}
}
dt = dt.AddDays();
year = dt.Year;
month = dt.Month;
date = dt.Day;
l = calElement(year, month, date);
lmd = FormatDate((int)l[], (int)l[]);
if (lmd.Equals("")) cd.cnFtvl = "除夕";
return cd;
}
#endregion
} /// <summary>
/// 中国日历
/// </summary>
//-------------------------------------------------------------------------------
//调用:
//ChineseCalendar c = new ChineseCalendar(new DateTime(1990, 01, 15));
//StringBuilder dayInfo = new StringBuilder();
//dayInfo.Append("阳历:" + c.DateString + "\r\n");
//dayInfo.Append("农历:" + c.ChineseDateString + "\r\n");
//dayInfo.Append("星期:" + c.WeekDayStr);
//dayInfo.Append("时辰:" + c.ChineseHour + "\r\n");
//dayInfo.Append("属相:" + c.AnimalString + "\r\n");
//dayInfo.Append("节气:" + c.ChineseTwentyFourDay + "\r\n");
//dayInfo.Append("前一个节气:" + c.ChineseTwentyFourPrevDay + "\r\n");
//dayInfo.Append("下一个节气:" + c.ChineseTwentyFourNextDay + "\r\n");
//dayInfo.Append("节日:" + c.DateHoliday + "\r\n");
//dayInfo.Append("干支:" + c.GanZhiDateString + "\r\n");
//dayInfo.Append("星宿:" + c.ChineseConstellation + "\r\n");
//dayInfo.Append("星座:" + c.Constellation + "\r\n");
//-------------------------------------------------------------------------------
public class ChineseCalendar
{
#region 内部结构
/// <summary>
/// 阳历
/// </summary>
private struct SolarHolidayStruct
{
public int Month;
public int Day;
public int Recess; //假期长度
public string HolidayName;
public SolarHolidayStruct(int month, int day, int recess, string name)
{
Month = month;
Day = day;
Recess = recess;
HolidayName = name;
}
} /// <summary>
/// 农历
/// </summary>
private struct LunarHolidayStruct
{
public int Month;
public int Day;
public int Recess;
public string HolidayName; public LunarHolidayStruct(int month, int day, int recess, string name)
{
Month = month;
Day = day;
Recess = recess;
HolidayName = name;
}
} private struct WeekHolidayStruct
{
public int Month;
public int WeekAtMonth;
public int WeekDay;
public string HolidayName; public WeekHolidayStruct(int month, int weekAtMonth, int weekDay, string name)
{
Month = month;
WeekAtMonth = weekAtMonth;
WeekDay = weekDay;
HolidayName = name;
}
}
#endregion #region 内部变量
private DateTime _date;
private DateTime _datetime;
private int _cYear;
private int _cMonth;
private int _cDay;
private bool _cIsLeapMonth; //当月是否闰月
private bool _cIsLeapYear; //当年是否有闰月
#endregion #region 基础数据
#region 基本常量
private const int MinYear = ;
private const int MaxYear = ;
private static DateTime MinDay = new DateTime(, , );
private static DateTime MaxDay = new DateTime(, , );
private const int GanZhiStartYear = ; //干支计算起始年
private static DateTime GanZhiStartDay = new DateTime(, , );//起始日
private const string HZNum = "零一二三四五六七八九";
private const int AnimalStartYear = ; //1900年为鼠年
private static DateTime ChineseConstellationReferDay = new DateTime(, , );//28星宿参考值,本日为角
#endregion #region 阴历数据
/// <summary>
/// 来源于网上的农历数据
/// </summary>
/// <remarks>
/// 数据结构如下,共使用17位数据
/// 第17位:表示闰月天数,0表示29天 1表示30天
/// 第16位-第5位(共12位)表示12个月,其中第16位表示第一月,如果该月为30天则为1,29天为0
/// 第4位-第1位(共4位)表示闰月是哪个月,如果当年没有闰月,则置0
///</remarks>
private static int[] LunarDateArray = new int[]{
0x04BD8,0x04AE0,0x0A570,0x054D5,0x0D260,0x0D950,0x16554,0x056A0,0x09AD0,0x055D2,
0x04AE0,0x0A5B6,0x0A4D0,0x0D250,0x1D255,0x0B540,0x0D6A0,0x0ADA2,0x095B0,0x14977,
0x04970,0x0A4B0,0x0B4B5,0x06A50,0x06D40,0x1AB54,0x02B60,0x09570,0x052F2,0x04970,
0x06566,0x0D4A0,0x0EA50,0x06E95,0x05AD0,0x02B60,0x186E3,0x092E0,0x1C8D7,0x0C950,
0x0D4A0,0x1D8A6,0x0B550,0x056A0,0x1A5B4,0x025D0,0x092D0,0x0D2B2,0x0A950,0x0B557,
0x06CA0,0x0B550,0x15355,0x04DA0,0x0A5B0,0x14573,0x052B0,0x0A9A8,0x0E950,0x06AA0,
0x0AEA6,0x0AB50,0x04B60,0x0AAE4,0x0A570,0x05260,0x0F263,0x0D950,0x05B57,0x056A0,
0x096D0,0x04DD5,0x04AD0,0x0A4D0,0x0D4D4,0x0D250,0x0D558,0x0B540,0x0B6A0,0x195A6,
0x095B0,0x049B0,0x0A974,0x0A4B0,0x0B27A,0x06A50,0x06D40,0x0AF46,0x0AB60,0x09570,
0x04AF5,0x04970,0x064B0,0x074A3,0x0EA50,0x06B58,0x055C0,0x0AB60,0x096D5,0x092E0,
0x0C960,0x0D954,0x0D4A0,0x0DA50,0x07552,0x056A0,0x0ABB7,0x025D0,0x092D0,0x0CAB5,
0x0A950,0x0B4A0,0x0BAA4,0x0AD50,0x055D9,0x04BA0,0x0A5B0,0x15176,0x052B0,0x0A930,
0x07954,0x06AA0,0x0AD50,0x05B52,0x04B60,0x0A6E6,0x0A4E0,0x0D260,0x0EA65,0x0D530,
0x05AA0,0x076A3,0x096D0,0x04BD7,0x04AD0,0x0A4D0,0x1D0B6,0x0D250,0x0D520,0x0DD45,
0x0B5A0,0x056D0,0x055B2,0x049B0,0x0A577,0x0A4B0,0x0AA50,0x1B255,0x06D20,0x0ADA0,
0x14B63
}; #endregion #region 星座名称
private static string[] _constellationName =
{
"白羊座", "金牛座", "双子座",
"巨蟹座", "狮子座", "处女座",
"天秤座", "天蝎座", "射手座",
"摩羯座", "水瓶座", "双鱼座"
};
#endregion #region 二十四节气
private static string[] _lunarHolidayName =
{
"小寒", "大寒", "立春", "雨水",
"惊蛰", "春分", "清明", "谷雨",
"立夏", "小满", "芒种", "夏至",
"小暑", "大暑", "立秋", "处暑",
"白露", "秋分", "寒露", "霜降",
"立冬", "小雪", "大雪", "冬至"
};
#endregion #region 二十八星宿
private static string[] _chineseConstellationName =
{
//四 五 六 日 一 二 三
"角木蛟","亢金龙","女土蝠","房日兔","心月狐","尾火虎","箕水豹",
"斗木獬","牛金牛","氐土貉","虚日鼠","危月燕","室火猪","壁水獝",
"奎木狼","娄金狗","胃土彘","昴日鸡","毕月乌","觜火猴","参水猿",
"井木犴","鬼金羊","柳土獐","星日马","张月鹿","翼火蛇","轸水蚓"
};
#endregion #region 节气数据
private static string[] SolarTerm = new string[] { "小寒", "大寒", "立春", "雨水", "惊蛰", "春分", "清明", "谷雨", "立夏", "小满", "芒种", "夏至", "小暑", "大暑", "立秋", "处暑", "白露", "秋分", "寒露", "霜降", "立冬", "小雪", "大雪", "冬至" };
private static int[] sTermInfo = new int[] { , , , , , , , , , , , , , , , , , , , , , , , };
#endregion #region 农历相关数据
private static string ganStr = "甲乙丙丁戊己庚辛壬癸";
private static string zhiStr = "子丑寅卯辰巳午未申酉戌亥";
private static string animalStr = "鼠牛虎兔龙蛇马羊猴鸡狗猪";
private static string nStr1 = "日一二三四五六七八九";
private static string nStr2 = "初十廿卅";
private static string[] _monthString =
{
"出错","正月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","腊月"
};
#endregion #region 按公历计算的节日
private static SolarHolidayStruct[] sHolidayInfo = new SolarHolidayStruct[]{
new SolarHolidayStruct(, , , "元旦"),
new SolarHolidayStruct(, , , "世界湿地日"),
new SolarHolidayStruct(, , , "国际气象节"),
new SolarHolidayStruct(, , , "情人节"),
new SolarHolidayStruct(, , , "国际海豹日"),
new SolarHolidayStruct(, , , "学雷锋纪念日"),
new SolarHolidayStruct(, , , "妇女节"),
new SolarHolidayStruct(, , , "植树节 孙中山逝世纪念日"),
new SolarHolidayStruct(, , , "国际警察日"),
new SolarHolidayStruct(, , , "消费者权益日"),
new SolarHolidayStruct(, , , "中国国医节 国际航海日"),
new SolarHolidayStruct(, , , "世界森林日 消除种族歧视国际日 世界儿歌日"),
new SolarHolidayStruct(, , , "世界水日"),
new SolarHolidayStruct(, , , "世界防治结核病日"),
new SolarHolidayStruct(, , , "愚人节"),
new SolarHolidayStruct(, , , "世界卫生日"),
new SolarHolidayStruct(, , , "世界地球日"),
new SolarHolidayStruct(, , , "劳动节"),
new SolarHolidayStruct(, , , "劳动节假日"),
new SolarHolidayStruct(, , , "劳动节假日"),
new SolarHolidayStruct(, , , "青年节"),
new SolarHolidayStruct(, , , "世界红十字日"),
new SolarHolidayStruct(, , , "国际护士节"),
new SolarHolidayStruct(, , , "世界无烟日"),
new SolarHolidayStruct(, , , "国际儿童节"),
new SolarHolidayStruct(, , , "世界环境保护日"),
new SolarHolidayStruct(, , , "国际禁毒日"),
new SolarHolidayStruct(, , , "建党节 香港回归纪念 世界建筑日"),
new SolarHolidayStruct(, , , "世界人口日"),
new SolarHolidayStruct(, , , "建军节"),
new SolarHolidayStruct(, , , "中国男子节 父亲节"),
new SolarHolidayStruct(, , , "抗日战争胜利纪念"),
new SolarHolidayStruct(, , , "毛主席逝世纪念"),
new SolarHolidayStruct(, , , "教师节"),
new SolarHolidayStruct(, , , "九·一八事变纪念日"),
new SolarHolidayStruct(, , , "国际爱牙日"),
new SolarHolidayStruct(, , , "世界旅游日"),
new SolarHolidayStruct(, , , "孔子诞辰"),
new SolarHolidayStruct(, , , "国庆节 国际音乐日"),
new SolarHolidayStruct(, , , "国庆节假日"),
new SolarHolidayStruct(, , , "国庆节假日"),
new SolarHolidayStruct(, , , "老人节"),
new SolarHolidayStruct(, , , "联合国日"),
new SolarHolidayStruct(, , , "世界青年节"),
new SolarHolidayStruct(, , , "孙中山诞辰纪念"),
new SolarHolidayStruct(, , , "世界艾滋病日"),
new SolarHolidayStruct(, , , "世界残疾人日"),
new SolarHolidayStruct(, , , "澳门回归纪念"),
new SolarHolidayStruct(, , , "平安夜"),
new SolarHolidayStruct(, , , "圣诞节"),
new SolarHolidayStruct(, , , "毛主席诞辰纪念")
};
#endregion #region 按农历计算的节日
private static LunarHolidayStruct[] lHolidayInfo = new LunarHolidayStruct[]{
new LunarHolidayStruct(, , , "春节"),
new LunarHolidayStruct(, , , "元宵节"),
new LunarHolidayStruct(, , , "端午节"),
new LunarHolidayStruct(, , , "七夕情人节"),
new LunarHolidayStruct(, , , "中元节 盂兰盆节"),
new LunarHolidayStruct(, , , "中秋节"),
new LunarHolidayStruct(, , , "重阳节"),
new LunarHolidayStruct(, , , "腊八节"),
new LunarHolidayStruct(, , , "北方小年(扫房)"),
new LunarHolidayStruct(, , , "南方小年(掸尘)"),
//new LunarHolidayStruct(12, 30, 0, "除夕") //注意除夕需要其它方法进行计算
};
#endregion #region 按某月第几个星期几
private static WeekHolidayStruct[] wHolidayInfo = new WeekHolidayStruct[]{
new WeekHolidayStruct(, , , "母亲节"),
new WeekHolidayStruct(, , , "全国助残日"),
new WeekHolidayStruct(, , , "父亲节"),
new WeekHolidayStruct(, , , "国际和平日"),
new WeekHolidayStruct(, , , "国际聋人节"),
new WeekHolidayStruct(, , , "国际住房日"),
new WeekHolidayStruct(, , , "国际减轻自然灾害日"),
new WeekHolidayStruct(, , , "感恩节")
};
#endregion
#endregion #region 构造函数
#region 公历日期初始化
/// <summary>
/// 用一个标准的公历日期来初使化
/// </summary>
public ChineseCalendar(DateTime dt)
{
int i;
int leap;
int temp;
int offset; CheckDateLimit(dt); _date = dt.Date;
_datetime = dt; //农历日期计算部分
leap = ;
temp = ; //计算两天的基本差距
TimeSpan ts = _date - ChineseCalendar.MinDay;
offset = ts.Days; for (i = MinYear; i <= MaxYear; i++)
{
//求当年农历年天数
temp = GetChineseYearDays(i);
if (offset - temp < )
break;
else
{
offset = offset - temp;
}
}
_cYear = i; //计算该年闰哪个月
leap = GetChineseLeapMonth(_cYear); //设定当年是否有闰月
if (leap > )
{
_cIsLeapYear = true;
}
else
{
_cIsLeapYear = false;
} _cIsLeapMonth = false;
for (i = ; i <= ; i++)
{
//闰月
if ((leap > ) && (i == leap + ) && (_cIsLeapMonth == false))
{
_cIsLeapMonth = true;
i = i - ;
temp = GetChineseLeapMonthDays(_cYear); //计算闰月天数
}
else
{
_cIsLeapMonth = false;
temp = GetChineseMonthDays(_cYear, i); //计算非闰月天数
} offset = offset - temp;
if (offset <= ) break;
} offset = offset + temp;
_cMonth = i;
_cDay = offset;
}
#endregion #region 农历日期初始化
/// <summary>
/// 用农历的日期来初使化
/// </summary>
/// <param name="cy">农历年</param>
/// <param name="cm">农历月</param>
/// <param name="cd">农历日</param>
/// <param name="LeapFlag">闰月标志</param>
public ChineseCalendar(int cy, int cm, int cd, bool leapMonthFlag)
{
int i, leap, Temp, offset; CheckChineseDateLimit(cy, cm, cd, leapMonthFlag); _cYear = cy;
_cMonth = cm;
_cDay = cd; offset = ; for (i = MinYear; i < cy; i++)
{
//求当年农历年天数
Temp = GetChineseYearDays(i);
offset = offset + Temp;
} //计算该年应该闰哪个月
leap = GetChineseLeapMonth(cy);
if (leap != )
{
this._cIsLeapYear = true;
}
else
{
this._cIsLeapYear = false;
} if (cm != leap)
{
//当前日期并非闰月
_cIsLeapMonth = false;
}
else
{
//使用用户输入的是否闰月月份
_cIsLeapMonth = leapMonthFlag;
} //当年没有闰月||计算月份小于闰月
if ((_cIsLeapYear == false) || (cm < leap))
{
for (i = ; i < cm; i++)
{
Temp = GetChineseMonthDays(cy, i);//计算非闰月天数
offset = offset + Temp;
} //检查日期是否大于最大天
if (cd > GetChineseMonthDays(cy, cm))
{
throw new Exception("不合法的农历日期");
}
//加上当月的天数
offset = offset + cd;
} //是闰年,且计算月份大于或等于闰月
else
{
for (i = ; i < cm; i++)
{
//计算非闰月天数
Temp = GetChineseMonthDays(cy, i);
offset = offset + Temp;
} //计算月大于闰月
if (cm > leap)
{
Temp = GetChineseLeapMonthDays(cy); //计算闰月天数
offset = offset + Temp; //加上闰月天数 if (cd > GetChineseMonthDays(cy, cm))
{
throw new Exception("不合法的农历日期");
}
offset = offset + cd;
} //计算月等于闰月
else
{
//如果需要计算的是闰月,则应首先加上与闰月对应的普通月的天数
if (this._cIsLeapMonth == true) //计算月为闰月
{
Temp = GetChineseMonthDays(cy, cm); //计算非闰月天数
offset = offset + Temp;
} if (cd > GetChineseLeapMonthDays(cy))
{
throw new Exception("不合法的农历日期");
}
offset = offset + cd;
}
}
_date = MinDay.AddDays(offset);
}
#endregion
#endregion #region 私有函数
#region GetChineseMonthDays
/// <summary>
/// //传回农历y年m月的总天数
/// </summary>
private int GetChineseMonthDays(int year, int month)
{
if (BitTest32((LunarDateArray[year - MinYear] & 0x0000FFFF), ( - month)))
{
return ;
}
else
{
return ;
}
}
#endregion #region GetChineseLeapMonth
/// <summary>
/// 传回农历 y年闰哪个月 1-12 , 没闰传回 0
/// </summary>
private int GetChineseLeapMonth(int year)
{
return LunarDateArray[year - MinYear] & 0xF;
}
#endregion #region GetChineseLeapMonthDays
/// <summary>
/// 传回农历y年闰月的天数
/// </summary>
private int GetChineseLeapMonthDays(int year)
{
if (GetChineseLeapMonth(year) != )
{
if ((LunarDateArray[year - MinYear] & 0x10000) != )
{
return ;
}
else
{
return ;
}
}
else
{
return ;
}
}
#endregion #region GetChineseYearDays
/// <summary>
/// 取农历年一年的天数
/// </summary>
private int GetChineseYearDays(int year)
{
int i, f, sumDay, info; sumDay = ; //29天*12个月
i = 0x8000;
info = LunarDateArray[year - MinYear] & 0x0FFFF; //计算12个月中有多少天为30天
for (int m = ; m < ; m++)
{
f = info & i;
if (f != )
{
sumDay++;
}
i = i >> ;
}
return sumDay + GetChineseLeapMonthDays(year);
}
#endregion #region GetChineseHour
/// <summary>
/// 获得当前时间的时辰
/// </summary>
private string GetChineseHour(DateTime dt)
{
int _hour, _minute, offset, i;
int indexGan;
//string ganHour, zhiHour;
string tmpGan; //计算时辰的地支
_hour = dt.Hour; //获得当前时间小时
_minute = dt.Minute; //获得当前时间分钟 if (_minute != ) _hour += ;
offset = _hour / ;
if (offset >= ) offset = ;
//zhiHour = zhiStr[offset].ToString(); //计算天干
TimeSpan ts = this._date - GanZhiStartDay;
i = ts.Days % ; //ganStr[i % 10] 为日的天干,(n*2-1) %10得出地支对应,n从1开始
indexGan = ((i % + ) * - ) % - ; tmpGan = ganStr.Substring(indexGan) + ganStr.Substring(, indexGan + );//凑齐12位
//ganHour = ganStr[((i % 10 + 1) * 2 - 1) % 10 - 1].ToString(); return tmpGan[offset].ToString() + zhiStr[offset].ToString();
}
#endregion #region CheckDateLimit
/// <summary>
/// 检查公历日期是否符合要求
/// </summary>
private void CheckDateLimit(DateTime dt)
{
if ((dt < MinDay) || (dt > MaxDay))
{
throw new Exception("超出可转换的日期");
}
}
#endregion #region CheckChineseDateLimit
/// <summary>
/// 检查农历日期是否合理
/// </summary>
private void CheckChineseDateLimit(int year, int month, int day, bool leapMonth)
{
if ((year < MinYear) || (year > MaxYear))
{
throw new Exception("非法农历日期");
}
if ((month < ) || (month > ))
{
throw new Exception("非法农历日期");
}
if ((day < ) || (day > )) //中国的月最多30天
{
throw new Exception("非法农历日期");
}
int leap = GetChineseLeapMonth(year);// 计算该年应该闰哪个月
if ((leapMonth == true) && (month != leap))
{
throw new Exception("非法农历日期");
}
}
#endregion #region ConvertNumToChineseNum
/// <summary>
/// 将0-9转成汉字形式
/// </summary>
private string ConvertNumToChineseNum(char n)
{
if ((n < '') || (n > '')) return "";
switch (n)
{
case '':
return HZNum[].ToString();
case '':
return HZNum[].ToString();
case '':
return HZNum[].ToString();
case '':
return HZNum[].ToString();
case '':
return HZNum[].ToString();
case '':
return HZNum[].ToString();
case '':
return HZNum[].ToString();
case '':
return HZNum[].ToString();
case '':
return HZNum[].ToString();
case '':
return HZNum[].ToString();
default:
return "";
}
}
#endregion #region BitTest32
/// <summary>
/// 测试某位是否为真
/// </summary>
private bool BitTest32(int num, int bitpostion)
{
if ((bitpostion > ) || (bitpostion < ))
throw new Exception("Error Param: bitpostion[0-31]:" + bitpostion.ToString()); int bit = << bitpostion; if ((num & bit) == )
{
return false;
}
else
{
return true;
}
}
#endregion #region ConvertDayOfWeek
/// <summary>
/// 将星期几转成数字表示
/// </summary>
private int ConvertDayOfWeek(DayOfWeek dayOfWeek)
{
switch (dayOfWeek)
{
case DayOfWeek.Sunday:
return ;
case DayOfWeek.Monday:
return ;
case DayOfWeek.Tuesday:
return ;
case DayOfWeek.Wednesday:
return ;
case DayOfWeek.Thursday:
return ;
case DayOfWeek.Friday:
return ;
case DayOfWeek.Saturday:
return ;
default:
return ;
}
}
#endregion #region CompareWeekDayHoliday
/// <summary>
/// 比较当天是不是指定的第周几
/// </summary>
private bool CompareWeekDayHoliday(DateTime date, int month, int week, int day)
{
bool ret = false; if (date.Month == month) //月份相同
{
if (ConvertDayOfWeek(date.DayOfWeek) == day) //星期几相同
{
DateTime firstDay = new DateTime(date.Year, date.Month, );//生成当月第一天
int i = ConvertDayOfWeek(firstDay.DayOfWeek);
int firWeekDays = - ConvertDayOfWeek(firstDay.DayOfWeek) + ; //计算第一周剩余天数 if (i > day)
{
if ((week - ) * + day + firWeekDays == date.Day)
{
ret = true;
}
}
else
{
if (day + firWeekDays + (week - ) * == date.Day)
{
ret = true;
}
}
}
} return ret;
}
#endregion
#endregion #region 属性
#region 节日
#region newCalendarHoliday
/// <summary>
/// 计算中国农历节日
/// </summary>
public string newCalendarHoliday
{
get
{
string tempStr = "";
if (this._cIsLeapMonth == false) //闰月不计算节日
{
foreach (LunarHolidayStruct lh in lHolidayInfo)
{
if ((lh.Month == this._cMonth) && (lh.Day == this._cDay))
{ tempStr = lh.HolidayName;
break; }
} //对除夕进行特别处理
if (this._cMonth == )
{
int i = GetChineseMonthDays(this._cYear, ); //计算当年农历12月的总天数
if (this._cDay == i) //如果为最后一天
{
tempStr = "除夕";
}
}
}
return tempStr;
}
}
#endregion #region WeekDayHoliday
/// <summary>
/// 按某月第几周第几日计算的节日
/// </summary>
public string WeekDayHoliday
{
get
{
string tempStr = "";
foreach (WeekHolidayStruct wh in wHolidayInfo)
{
if (CompareWeekDayHoliday(_date, wh.Month, wh.WeekAtMonth, wh.WeekDay))
{
tempStr = wh.HolidayName;
break;
}
}
return tempStr;
}
}
#endregion #region DateHoliday
/// <summary>
/// 按公历日计算的节日
/// </summary>
public string DateHoliday
{
get
{
string tempStr = ""; foreach (SolarHolidayStruct sh in sHolidayInfo)
{
if ((sh.Month == _date.Month) && (sh.Day == _date.Day))
{
tempStr = sh.HolidayName;
break;
}
}
return tempStr;
}
}
#endregion
#endregion #region 公历日期
#region Date
/// <summary>
/// 取对应的公历日期
/// </summary>
public DateTime Date
{
get { return _date; }
set { _date = value; }
}
#endregion #region WeekDay
/// <summary>
/// 取星期几
/// </summary>
public DayOfWeek WeekDay
{
get { return _date.DayOfWeek; }
}
#endregion #region WeekDayStr
/// <summary>
/// 周几的字符
/// </summary>
public string WeekDayStr
{
get
{
switch (_date.DayOfWeek)
{
case DayOfWeek.Sunday:
return "星期日";
case DayOfWeek.Monday:
return "星期一";
case DayOfWeek.Tuesday:
return "星期二";
case DayOfWeek.Wednesday:
return "星期三";
case DayOfWeek.Thursday:
return "星期四";
case DayOfWeek.Friday:
return "星期五";
default:
return "星期六";
}
}
}
#endregion #region DateString
/// <summary>
/// 公历日期中文表示法 如一九九七年七月一日
/// </summary>
public string DateString
{
get
{
return "公元" + this._date.ToLongDateString();
}
}
#endregion #region IsLeapYear
/// <summary>
/// 当前是否公历闰年
/// </summary>
public bool IsLeapYear
{
get
{
return DateTime.IsLeapYear(this._date.Year);
}
}
#endregion #region ChineseConstellation
/// <summary>
/// 28星宿计算
/// </summary>
public string ChineseConstellation
{
get
{
int offset = ;
int modStarDay = ; TimeSpan ts = this._date - ChineseConstellationReferDay;
offset = ts.Days;
modStarDay = offset % ;
return (modStarDay >= ? _chineseConstellationName[modStarDay] : _chineseConstellationName[ + modStarDay]);
}
}
#endregion #region ChineseHour
/// <summary>
/// 时辰
/// </summary>
public string ChineseHour
{
get
{
return GetChineseHour(_datetime);
}
}
#endregion #endregion #region 农历日期
#region IsChineseLeapMonth
/// <summary>
/// 是否闰月
/// </summary>
public bool IsChineseLeapMonth
{
get { return this._cIsLeapMonth; }
}
#endregion #region IsChineseLeapYear
/// <summary>
/// 当年是否有闰月
/// </summary>
public bool IsChineseLeapYear
{
get
{
return this._cIsLeapYear;
}
}
#endregion #region ChineseDay
/// <summary>
/// 农历日
/// </summary>
public int ChineseDay
{
get { return this._cDay; }
}
#endregion #region ChineseDayString
/// <summary>
/// 农历日中文表示
/// </summary>
public string ChineseDayString
{
get
{
switch (this._cDay)
{
case :
return "";
case :
return "初十";
case :
return "二十";
case :
return "三十";
default:
return nStr2[(int)(_cDay / )].ToString() + nStr1[_cDay % ].ToString(); }
}
}
#endregion #region ChineseMonth
/// <summary>
/// 农历的月份
/// </summary>
public int ChineseMonth
{
get { return this._cMonth; }
}
#endregion #region ChineseMonthString
/// <summary>
/// 农历月份字符串
/// </summary>
public string ChineseMonthString
{
get
{
return _monthString[this._cMonth];
}
}
#endregion #region ChineseYear
/// <summary>
/// 取农历年份
/// </summary>
public int ChineseYear
{
get { return this._cYear; }
}
#endregion #region ChineseYearString
/// <summary>
/// 取农历年字符串如,一九九七年
/// </summary>
public string ChineseYearString
{
get
{
string tempStr = "";
string num = this._cYear.ToString();
for (int i = ; i < ; i++)
{
tempStr += ConvertNumToChineseNum(num[i]);
}
return tempStr + "年";
}
}
#endregion #region ChineseDateString
/// <summary>
/// 取农历日期表示法:农历一九九七年正月初五
/// </summary>
public string ChineseDateString
{
get
{
if (this._cIsLeapMonth == true)
{
return "农历" + ChineseYearString + "闰" + ChineseMonthString + ChineseDayString;
}
else
{
return "农历" + ChineseYearString + ChineseMonthString + ChineseDayString;
}
}
}
#endregion #region ChineseTwentyFourDay
/// <summary>
/// 定气法计算二十四节气,二十四节气是按地球公转来计算的,并非是阴历计算的
/// </summary>
/// <remarks>
/// 节气的定法有两种。古代历法采用的称为"恒气",即按时间把一年等分为24份,
/// 每一节气平均得15天有余,所以又称"平气"。现代农历采用的称为"定气",即
/// 按地球在轨道上的位置为标准,一周360°,两节气之间相隔15°。由于冬至时地
/// 球位于近日点附近,运动速度较快,因而太阳在黄道上移动15°的时间不到15天。
/// 夏至前后的情况正好相反,太阳在黄道上移动较慢,一个节气达16天之多。采用
/// 定气时可以保证春、秋两分必然在昼夜平分的那两天。
/// </remarks>
public string ChineseTwentyFourDay
{
get
{
DateTime baseDateAndTime = new DateTime(, , , , , ); //#1/6/1900 2:05:00 AM#
DateTime newDate;
double num;
int y;
string tempStr = ""; y = this._date.Year; for (int i = ; i <= ; i++)
{
num = 525948.76 * (y - ) + sTermInfo[i - ]; newDate = baseDateAndTime.AddMinutes(num);//按分钟计算
if (newDate.DayOfYear == _date.DayOfYear)
{
tempStr = SolarTerm[i - ];
break;
}
}
return tempStr;
}
} //当前日期前一个最近节气
public string ChineseTwentyFourPrevDay
{
get
{
DateTime baseDateAndTime = new DateTime(, , , , , ); //#1/6/1900 2:05:00 AM#
DateTime newDate;
double num;
int y;
string tempStr = ""; y = this._date.Year; for (int i = ; i >= ; i--)
{
num = 525948.76 * (y - ) + sTermInfo[i - ]; newDate = baseDateAndTime.AddMinutes(num);//按分钟计算 if (newDate.DayOfYear < _date.DayOfYear)
{
tempStr = string.Format("{0}[{1}]", SolarTerm[i - ], newDate.ToString("yyyy-MM-dd"));
break;
}
} return tempStr;
} } //当前日期后一个最近节气
public string ChineseTwentyFourNextDay
{
get
{
DateTime baseDateAndTime = new DateTime(, , , , , ); //#1/6/1900 2:05:00 AM#
DateTime newDate;
double num;
int y;
string tempStr = ""; y = this._date.Year; for (int i = ; i <= ; i++)
{
num = 525948.76 * (y - ) + sTermInfo[i - ]; newDate = baseDateAndTime.AddMinutes(num);//按分钟计算 if (newDate.DayOfYear > _date.DayOfYear)
{
tempStr = string.Format("{0}[{1}]", SolarTerm[i - ], newDate.ToString("yyyy-MM-dd"));
break;
}
}
return tempStr;
} }
#endregion
#endregion #region 星座
/// <summary>
/// 计算指定日期的星座序号
/// </summary>
public string Constellation
{
get
{
int index = ;
int y, m, d;
y = _date.Year;
m = _date.Month;
d = _date.Day;
y = m * + d; if (((y >= ) && (y <= ))) { index = ; }
else if ((y >= ) && (y <= )) { index = ; }
else if ((y >= ) && (y <= )) { index = ; }
else if ((y >= ) && (y <= )) { index = ; }
else if ((y >= ) && (y <= )) { index = ; }
else if ((y >= ) && (y <= )) { index = ; }
else if ((y >= ) && (y <= )) { index = ; }
else if ((y >= ) && (y <= )) { index = ; }
else if ((y >= ) && (y <= )) { index = ; }
else if ((y >= ) || (y <= )) { index = ; }
else if ((y >= ) && (y <= )) { index = ; }
else if ((y >= ) && (y <= )) { index = ; }
else { index = ; } return _constellationName[index];
}
}
#endregion #region 属相
#region Animal
/// <summary>
/// 计算属相的索引,注意虽然属相是以农历年来区别的,但是目前在实际使用中是按公历来计算的
/// 鼠年为1,其它类推
/// </summary>
public int Animal
{
get
{
int offset = _date.Year - AnimalStartYear;
return (offset % ) + ;
}
}
#endregion #region AnimalString
/// <summary>
/// 取属相字符串
/// </summary>
public string AnimalString
{
get
{
int offset = _date.Year - AnimalStartYear; //阳历计算
//int offset = this._cYear - AnimalStartYear; 农历计算
return animalStr[offset % ].ToString();
}
}
#endregion
#endregion #region 天干地支
#region GanZhiYearString
/// <summary>
/// 取农历年的干支表示法如 乙丑年
/// </summary>
public string GanZhiYearString
{
get
{
string tempStr;
int i = (this._cYear - GanZhiStartYear) % ; //计算干支
tempStr = ganStr[i % ].ToString() + zhiStr[i % ].ToString() + "年";
return tempStr;
}
}
#endregion #region GanZhiMonthString
/// <summary>
/// 取干支的月表示字符串,注意农历的闰月不记干支
/// </summary>
public string GanZhiMonthString
{
get
{
//每个月的地支总是固定的,而且总是从寅月开始
int zhiIndex;
string zhi;
if (this._cMonth > )
{
zhiIndex = this._cMonth - ;
}
else
{
zhiIndex = this._cMonth + ;
}
zhi = zhiStr[zhiIndex - ].ToString(); //根据当年的干支年的干来计算月干的第一个
int ganIndex = ;
string gan;
int i = (this._cYear - GanZhiStartYear) % ; //计算干支
switch (i % )
{
#region ...
case : //甲
ganIndex = ;
break;
case : //乙
ganIndex = ;
break;
case : //丙
ganIndex = ;
break;
case : //丁
ganIndex = ;
break;
case : //戊
ganIndex = ;
break;
case : //己
ganIndex = ;
break;
case : //庚
ganIndex = ;
break;
case : //辛
ganIndex = ;
break;
case : //壬
ganIndex = ;
break;
case : //癸
ganIndex = ;
break;
#endregion
}
gan = ganStr[(ganIndex + this._cMonth - ) % ].ToString(); return gan + zhi + "月";
}
}
#endregion #region GanZhiDayString
/// <summary>
/// 取干支日表示法
/// </summary>
public string GanZhiDayString
{
get
{
int i, offset;
TimeSpan ts = this._date - GanZhiStartDay;
offset = ts.Days;
i = offset % ;
return ganStr[i % ].ToString() + zhiStr[i % ].ToString() + "日";
}
}
#endregion #region GanZhiDateString
/// <summary>
/// 取当前日期的干支表示法如 甲子年乙丑月丙庚日
/// </summary>
public string GanZhiDateString
{
get
{
return GanZhiYearString + GanZhiMonthString + GanZhiDayString;
}
}
#endregion
#endregion
#endregion
}
}
调用:
ChineseCalendar c = new ChineseCalendar(DateTime.Now);
StringBuilder dayInfo = new StringBuilder();
dayInfo.Append("阳历:" + c.DateString + "\r\n");
dayInfo.Append("农历:" + c.ChineseDateString + "\r\n");
dayInfo.Append("星期:" + c.WeekDayStr);
dayInfo.Append("时辰:" + c.ChineseHour + "\r\n");
dayInfo.Append("属相:" + c.AnimalString + "\r\n");
dayInfo.Append("节气:" + c.ChineseTwentyFourDay + "\r\n");
dayInfo.Append("前一个节气:" + c.ChineseTwentyFourPrevDay + "\r\n");
dayInfo.Append("下一个节气:" + c.ChineseTwentyFourNextDay + "\r\n");
dayInfo.Append("节日:" + c.DateHoliday + "\r\n");
dayInfo.Append("干支:" + c.GanZhiDateString + "\r\n");
dayInfo.Append("星宿:" + c.ChineseConstellation + "\r\n");
dayInfo.Append("星座:" + c.Constellation + "\r\n");
Console.WriteLine(dayInfo.ToString());
结果:
已成熟的Utility有非常多,比如:https://github.com/99510309/Common.Utility
三、加密与解密
恺撒加密,War,Ybs,后移一位
网络安全:http://www.cnblogs.com/best/p/6823457.html
3.1、非对称加密
MD5即Message-Digest Algorithm 5(信息-摘要算法5),用于确保信息传输完整一致。是计算机广泛使用的杂凑算法之一(又译摘要算法、哈希算法),主流编程语言普遍已有MD5实现。将数据(如汉字)运算为另一固定长度值,是杂凑算法的基础原理,MD5的前身有MD2、MD3和MD4。
MD5算法具有以下特点:
1、压缩性:任意长度的数据,算出的MD5值长度都是固定的。
2、容易计算:从原数据计算出MD5值很容易。
3、抗修改性:对原数据进行任何改动,哪怕只修改1个字节,所得到的MD5值都有很大区别。
4、强抗碰撞:已知原数据和其MD5值,想找到一个具有相同MD5值的数据(即伪造数据)是非常困难的。
理论上加密后不能被解密,MD5,SHA1
一般用于作信息摘要,或加密数据库中的密码。
//textBox4.Text = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(textBox5.Text, "MD5");
textBox4.Text = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(textBox5.Text, "SHA1");
结果:
3.2、DES对称加密
DES是对称性加密里面常见一种,全称为Data Encryption Standard,即数据加密标准,是一种使用密钥加密的块算法。密钥长度是64位(bit),超过位数密钥被忽略。所谓对称性加密,加密和解密密钥相同。对称性加密一般会按照固定长度,把待加密字符串分成块。不足一整块或者刚好最后有特殊填充字符。往往跨语言做DES加密解密,经常会出现问题。往往是填充方式不对、或者编码不一致、或者选择加密解密模式(ECB,CBC,CTR,OFB,CFB,NCFB,NOFB)没有对应上造成。常见的填充模式有: 'pkcs5','pkcs7','iso10126','ansix923','zero' 类型,包括DES-ECB,DES-CBC,DES-CTR,DES-OFB,DES-CFB。
加密工具类:
namespace Chapter6
{
using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;
using System.Web.Security;
public class EnCrypt
{ //默认密钥向量
private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; /// <summary>
/// DES加密字符串
/// </summary>
/// <param name="encryptString">待加密的字符串</param>
/// <param name="encryptKey">加密密钥,要求为8位</param>
/// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
public static string DESEncode(string encryptString, string encryptKey)
{
encryptKey = formatStringTo8(encryptKey);
byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(, ));
byte[] rgbIV = Keys;
byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, , inputByteArray.Length);
cStream.FlushFinalBlock();
return Convert.ToBase64String(mStream.ToArray());
} /// <summary>
/// DES解密字符串
/// </summary>
/// <param name="decryptString">待解密的字符串</param>
/// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
/// <returns>解密成功返回解密后的字符串,失败返源串</returns>
public static string DESDecode(string decryptString, string decryptKey)
{
try
{
decryptKey = formatStringTo8(decryptKey);
byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
byte[] rgbIV = Keys;
byte[] inputByteArray = Convert.FromBase64String(decryptString);
DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider(); MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, , inputByteArray.Length);
cStream.FlushFinalBlock();
return Encoding.UTF8.GetString(mStream.ToArray());
}
catch
{
return "";
}
} /// <summary>
/// MD5函数
/// </summary>
/// <param name="str">原始字符串</param>
/// <returns>MD5结果</returns>
public static string MD5(string str)
{
byte[] b = Encoding.Default.GetBytes(str);
b = new MD5CryptoServiceProvider().ComputeHash(b);
string ret = "";
for (int i = ; i < b.Length; i++)
ret += b[i].ToString("x").PadLeft(, '');
return ret;
} /// <summary>
/// MD5函数
/// </summary>
/// <param name="str">原始字符串</param>
/// <param name="mod">16为16位摘要,32为32位摘要</param>
/// <returns>MD5结果</returns>
public static string MD5(string str, int mod)
{
if (mod == )
{
return MD5(str).Substring(, );
}
else
{
return MD5(str);
}
} /// <summary>
/// SHA256函数
/// </summary>
/// /// <param name="str">原始字符串</param>
/// <returns>SHA256结果</returns>
public static string SHA256(string str)
{
byte[] SHA256Data = Encoding.UTF8.GetBytes(str);
SHA256Managed Sha256 = new SHA256Managed();
byte[] Result = Sha256.ComputeHash(SHA256Data);
return Convert.ToBase64String(Result); //返回长度为44字节的字符串
} /// <summary>
/// 格式化密钥,保证八位格式
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string formatStringTo8(string str)
{
int len = str.Length;
if (len >= )
{
return str.Substring(, );
}
else
{
return str + "".Substring(, - len); }
} }
}
示例:
//加密
private void button6_Click(object sender, EventArgs e)
{
//指定要加密的文字与密码
txtString.Text = EnCrypt.DESEncode(txtString.Text, txtPassword.Text);
} //加密
private void button7_Click(object sender, EventArgs e)
{
//指定要解密的文字与密码
txtString.Text = EnCrypt.DESDecode(txtString.Text, txtPassword.Text);
}
运行结果:
四、作业
请使用工具类完成:MD5/SHA1/DES加密与解密,将存储在数据库中的密码加密,获得今天的农历,输入你的姓名获得拼音
五、视频与案例
params关键字、工具辅助类与、加密与解密的更多相关文章
- java独立小程序实现AES加密和解密
一.需求: web项目中配置文件配置的密码是明文的, 现在需要修改成密文, 加密方式采用AES, 于是写了个工具类用于加密和解密. 又因为这个密码是由客户来最终确定, 所以为了部署时方便起见, 写了个 ...
- 命令行工具aspnet_regiis.exe实现加密和解密web.config
命令行工具aspnet_regiis.exe,是一个类似于DOS的命令工具,称之为命令解释器.使用命令行工具加密和解密web.config文件中的数据库连接字符串时,只需要简单的语法命令即可. 加密语 ...
- java常用加密和解密工具类EncryptUtil.java
package cn.util; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; im ...
- 【Java】通过DES加密和解密工具,对字符串进行加密和解密操作
分享一个非常不错的字符串加密和解密的程序. 可以指定不同的密钥对同一字符串进行不同的加密操作,增强加密性能. Java代码如下: package com.app; import java.securi ...
- RSA加密和解密工具类
import org.apache.commons.codec.binary.Base64; import javax.crypto.Cipher; import java.security.*; i ...
- AES加密、解密工具类
AES加密.解密工具类代码如下: package com.util; import java.io.IOException; import java.io.UnsupportedEncodingExc ...
- 通过Go实现AES加密和解密工具
本文包含如下两个内容: AES加密介绍及实现原理 Go实现AES加密和解密工具 AES加密介绍及实现原理 AES( advanced encryption standard)使用相同密钥进行加密和解密 ...
- Java加密与解密笔记(二) 对称加密
前面的仅仅是做了编码或者摘要,下面看看真正的加密技术. DES public class DESUtil { static final String ALGORITHM = "DES&quo ...
- Java & PHP RSA 互通密钥、签名、验签、加密、解密
RSA加密算法是一种非对称加密算法.在公开密钥加密和电子商业中RSA被广泛使用.RSA是1977年由罗纳德·李维斯特(Ron Rivest).阿迪·萨莫尔(Adi Shamir)和伦纳德·阿德曼(Le ...
随机推荐
- unidbgrid单元格操作
unidbgrid单元格操作 //GRID里回车替换TABfunction cellkeydown(sender, td, cellIndex, record, tr, rowIndex, e, eO ...
- 取得cxgrid的表格的值,仔细看下面的代码
procedure TfrmMain.cxGridDBTableView_List_PSSJCustomDrawCell(Sender: TcxCustomGridTableView; ACanvas ...
- PICT用户手册 [转]
PICT 3.3 User's Guide Jacek Czerwonka, Test Lead, Microsoft Corporation Overview Using PICT to Combi ...
- 机器学习实战-ch3-决策树
决策树是一种新算法: 优点:计算复杂度不高,输出结果易于理解,对中间值的缺失不敏感,可以处理不相关特征数据.缺点:可能会产生过度匹配问题. 决策树算法可用于数据类型:数值型和标称型. 决策树的核心在于 ...
- 源自KPI交谈的思考
说明白一件事情不容易 前言 跟领导谈及下半年KPI的时候,问我什么打算/计划,在交谈过程中,有几个有意思的点 问题 Q: 目标是hold住服务端,那么怎么样才算hold住服务端? Q: 如何推动别人去 ...
- ContentControl as CC和ContentPresenter as CP的使用
1.CC为文本控件的父类,它继承为control,所以他是控件, 2.CP继承FrameworkElement,所以他是容器,相当于占位符 3.想让控件中能包含子控件就需要用CP,反之用CC就行.(不 ...
- MVC框架json数据展示程序(第一版)
模型原型:服务器的配置和运行状态信息. 设计要求:Json格式数据解析后,判断配置信息是否是新数据或者是否更新.如是新数据,则直接添加到数据库:若是数据更新,则更新数据库配置信息并更新运行状态信息:都 ...
- 【CJOJ2616】 【HZOI 2016】偏序 I(cdq分治,树状数组)
传送门 CJOJ Solution 考虑这是一个四维偏序对吧. 直接cdq套在一起,然后这题有两种实现方法(树状数组的更快!) 代码实现1(cdq+cdq+cdq) /* mail: mleautom ...
- 【062有新题】OCP 12c 062出现大量之前没有的新考题-16
choose one Which users are created and can be used for database and host management of your DBaaS da ...
- mysql查询语句分析 explain/desc用法
explain或desc显示了mysql如何使用索引来处理select语句以及连接表.可以帮助选择更好的索引和写出更优化的查询语句. explain 数据表 或 desc 数据表 显示数据表各字段含义 ...