使用C#编程计算某一年份的生肖
源代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//创建日历对象
System.Globalization.ChineseLunisolarCalendar cal = new System.Globalization.ChineseLunisolarCalendar();
//定义生肖字符串
string shuxiang = "鼠牛虎兔龙蛇马羊猴鸡狗猪";
long nf;
//传递文本参数
if (long.TryParse(textBox1.Text,out nf))
{
//将文本以指定格式的日期进行输出
DateTime rq = DateTime.ParseExact(textBox1.Text, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
//计算天干位置信息
int y = cal.GetSexagenaryYear(rq);
//计算地支位置信息,同时获取生肖
string tr = shuxiang.Substring(cal.GetTerrestrialBranch(y) - 1, 1);
textBox2.Text = tr;
}
else
{
MessageBox.Show("请输入正确年份","错误提示");
}
}
}
}
结语:
学会创建日历对象、TryParse()数值传递方法,以及DateTime类当中的ParseExact方法将文本以指定的日期格式进行输出,同时掌握日历类当中的GetSexagenaryYear计算天干的位置信息,以及GetTerrestrialBranch方法计算地支的位置信息。
喜欢的请关注收藏!