C# 使用DateTime 計算2日期 用月份Month計算 DateDiff
範例說明
一個可自行修改日期的TextBox,請自行修改
按下Button,會抓今天的日期再跟TextBox做計算
如輸入2014/01/01,測試日期是2014/4/1, 按下Button,會Label1會變3
如輸入2014/01/01,測試日期是2014/3/31,按下Button,會Label1會變2
這範例是滿1個月,才會計數1
============HTML==============================================
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" Text="2014/01/01"></asp:TextBox>
<asp:Button
ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
============ C# ==============================================
DateTime olddate =Convert.ToDateTime(TextBox1.Text);
DateTime newdate = DateTime.Now;
long months = Math.Abs((olddate.Month + (olddate.Year * 12)) - (newdate.Month + (newdate.Year * 12)));
Label1.Text = months.ToString();
沒有留言:
張貼留言