编写一个c程序,接受一个参数作为特定日期,并给出输出的总天数

本文关键字:一个 日期 输出 参数 程序 | 更新日期: 2023-09-27 18:24:44

am使用代码

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。

编写一个c程序,接受一个参数作为特定日期,并给出输出的总天数

您必须确保输入的字符串格式正确。由于.NET可以处理许多区域性,并且每个区域性都有不同的日期和时间格式,因此必须确保用户输入的字符串和当前区域性相匹配。请参阅带有格式提供程序的MS文章Convert.ToDateTime和Convert.ToDateTime中的示例。

有两种解决方案:

  1. 您可以在表单中添加验证(即regex)
  2. 您可以将日期输入过程拆分为3个字段:年、月、日,然后将日期对象创建为

    var dt=new DateTime(year, month, day);
    

    请参阅DateTime构造函数

另一件事是,您可以使用TimeSpan类来代替自己减去日期。它很简单:

var span=DateTime.Now - dt;

试试这个,我已经检查过了

        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