编写一个c#程序,该程序接受一个参数作为特定日期,并给出输出总天数
我在使用代码编写一个c#程序,该程序接受一个参数作为特定日期,并给出输出总天数,c#,C#,我在使用代码 DateTime dt = new DateTime(); int currentyear, currentmonth, borthmonth, birthyear, years, month; dt = Convert.ToDateTime(txt_age1.Text); currentyear = Convert.ToInt32(DateTime.Now.Year); currentmonth = Convert.ToInt32(DateTime.Now.Month); bir
DateTime dt = new DateTime();
int currentyear, currentmonth, borthmonth, birthyear, years, month;
dt = Convert.ToDateTime(txt_age1.Text);
currentyear = Convert.ToInt32(DateTime.Now.Year);
currentmonth = Convert.ToInt32(DateTime.Now.Month);
birthyear = Convert.ToInt32(DateTime.Now.Year);
borthmonth = Convert.ToInt32(DateTime.Now.Month);
years = currentyear - birthyear;
if (currentmonth - borthmonth > 0)
{
month = Convert.ToInt32(currentmonth - borthmonth);
}
else
{
years = years - 1;
month = Convert.ToInt32((12 - borthmonth) + currentmonth);
}
txt_age1.Text = years.ToString() + "/" + month.ToString();
但是我得到了这个错误
字符串未被识别为有效的日期时间
试试这个,我查过了
DateTime dt = new DateTime();
int currentyear, currentmonth, borthmonth, birthyear, years, month;
dt = Convert.ToDateTime("1993-08-04");//here i assume you are taking date of birth
currentyear = Convert.ToInt32(DateTime.Now.Year);
currentmonth = Convert.ToInt32(DateTime.Now.Month);
birthyear = Convert.ToInt32(dt.Year);
borthmonth = Convert.ToInt32(dt.Month);
years = currentyear - birthyear;
if (currentmonth - borthmonth > 0)
{
month = Convert.ToInt32(currentmonth - borthmonth);
}
else
{
years = years - 1;
month = Convert.ToInt32((12 - borthmonth) + currentmonth);
}
Console.WriteLine(years.ToString() + "/" + month.ToString());// here i am printing the result into console
您必须确保输入的字符串格式正确。由于.NET可以处理许多区域性,并且每个区域性都有不同的日期和时间格式,所以必须确保用户输入的字符串和当前区域性相匹配。请参阅MS文章和中的示例 有两种解决方案:
var dt=new DateTime(year, month, day);
看var span=DateTime.Now - dt;
您从文本框名称txt_age1.Text中获取的输入是什么?我猜你是在记出生日期吧?