用到两个datatimepicker控件datatimepicker1和datatimepicker2 需要计算出两个控件显示日期之间的天数和经历的月份
如datatimepicker1=2008-10-3 datatimepicker2 =2009-1-5 计算出相隔的天数 并给出经历的月份(10、11、12、1)
怎么编程实现
如datatimepicker1=2008-10-3 datatimepicker2 =2009-1-5 计算出相隔的天数 并给出经历的月份(10、11、12、1)
怎么编程实现
DateTime dt1 = DateTime.Now;
DateTime dt2 = DateTime.Now.AddDays(-7);
TimeSpan ts = dt1 - dt2;
int days = ts.Days; //dt1和dt2相差多少天
DateTime d2 = datatimepicker1.Value;
double s = d1.SubTract(d2).TotalDays;
MessageBox.Show(s.Tostring());//相隔的天数
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;namespace WindowsApplication41
{
public partial class Form1 : Form
{
DataGridView DGV = new DataGridView(); public Form1()
{
InitializeComponent(); DateTimePicker DTP1 = new DateTimePicker();
DTP1.Parent = this;
DateTimePicker DTP2 = new DateTimePicker();
DTP2.Parent = this; DTP1.Value = DateTime.Parse("2008-10-3");
DTP2.Value = DateTime.Parse("2009-1-5"); MessageBox.Show("相隔天数: " + (DTP2.Value - DTP1.Value).TotalDays.ToString());
String S = String.Empty;
for (DateTime DT = DTP1.Value; DT <= DTP2.Value; DT = DT.AddMonths(1))
S += DT.Month.ToString() + " ";
MessageBox.Show("经历月份: " + S);
}
}
}
直接把日期传过来,用这个函数可以实现select Datediff(d,'2009-6-1',getdate())
DateTime d1 = datatimepicker2.Value;
DateTime d2 = datatimepicker1.Value;
DateTime d3= d2;
while(d3<d1)
{
Console.WriteLine(d3.Month.ToString());
d3= d3.AddMonths(1);
}
DateTime d2 = datatimepicker1.Value;
double s = d1.SubTract(d2).TotalDays;
MessageBox.Show(s.Tostring());//相隔的天数
//出经历的月份(10、11、12、1)
DateTime d1 = datatimepicker2.Value;
DateTime d2 = datatimepicker1.Value;
DateTime d3= d2;
while(d3 <d1)
{
Console.WriteLine(d3.Month.ToString());
d3= d3.AddMonths(1);
}
DateTime d2 = new DateTime(2009, 10, 1);
for (DateTime dt = new DateTime(d1.Year, d1.Month, 1); dt <= d2; dt = dt.AddMonths(1))
{
Console.WriteLine(dt.Month);
}
Console.Read();
改下
for (DateTime DT = DTP1.Value.AddDays(-DTP1.Value.Day + 1); DT <= DTP2.Value; DT = DT.AddMonths(1))
S += DT.Month.ToString() + " ";
MessageBox.Show("经历月份: " + S);
{
string dateDiff=null;
try
{
TimeSpan ts1=new TimeSpan(DateTime1.Ticks);
TimeSpan ts2=new TimeSpan(DateTime2.Ticks);
TimeSpan ts=ts1.Subtract(ts2).Duration();
dateDiff=ts.Days.ToString()+"天"
}
catch
{ }
return dateDiff;
}
方法都被他们说完了
如datatimepicker1=2008-10-3 datatimepicker2 =2009-1-5 计算出相隔的天数 并给出经历的月份(10、11、12、1)
得出4???