C#提取数据库中日期的年份与当前日期的年份的差值

计算工龄,用C#实现,数据库字段birthday,数据类型为datetime,怎么提取数据库的年份出来,然后用当前日期的年份减去这个birthday的年份,得出工龄的方法.麻烦从打开数据库开始写起,谢谢各位帮忙.

第1个回答  2013-07-24
呵呵 偷一下懒sqlconnection con = new sqlconnection("连接字符串");int ID = 设置要查询的ID;string str = "select birthday from table where id=" + "'" + ID + "'";(如用于商用则需要使用参数话查询)con.open();sqlcommand cmd = new sqlcommand(str,con);sqldatareader dr = cmd.Ex……datareader();这里记不住了0_0;if(dr.read()){ int 工龄= datatime.now.year - (int)(dr[0].tostring()).SubString(0,4);}con.close();本回答被网友采纳
第2个回答  2013-07-24
我开发系统时是这样处理的,希望对你有用. DropDownList5促发事件. protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{ string strid = Page.Request.QueryString["employeeid"];
String strConn = ConfigurationManager.AppSettings["SQLConnectionString"];
SqlConnection sqlconn = new SqlConnection(strConn);
sqlconn.Open();
string sqlstrshow = "select * from employee where employeeid='" + strid + "'";
SqlDataAdapter myapter = new SqlDataAdapter(sqlstrshow, sqlconn);
DataSet mydset = new DataSet();
myapter.Fill(mydset, "employee"); DataRowView mydrview = mydset.Tables["employee"].DefaultView[0]; TextBox29.Text = Convert.ToDateTime(mydrview.Row["hiredate"].ToString()).ToShortDateString();//提取数据库的入职日期}
protected void DropDownList5_SelectedIndexChanged(object sender, EventArgs e)
{
int nowmonth = System.DateTime.Now.Year * 12 + System.DateTime.Now.Month;//当前日期
int oldmonth = Convert.ToInt32(Convert.ToString(Convert.ToDateTime(TextBox29.Text).Year * 12)) + Convert.ToInt32(Convert.ToString(Convert.ToDateTime(TextBox29.Text).Month));//数据库的入职时间
Label8.Text = Convert.ToString((nowmonth - oldmonth) / 12);//工龄,月份相减取整 }
第3个回答  2013-07-24
sqlconnection con = new sqlconnection("连接字符串");int ID = 设置要查询的ID;string str = "select birthday from table where id=" + "'" + ID + "'";(如用于商用则需要使用参数话查询)con.open();sqlcommand cmd = new sqlcommand(str,con);sqldatareader dr = cmd.Ex……datareader();这里记不住了0_0;if(dr.read()){ datatime dt = datatime.now - datatime.parse(dr[0].tostring());}con.close();手写版,只供参考
相似回答
大家正在搜