Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/security/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
编写一个c#程序,该程序接受一个参数作为特定日期,并给出输出总天数_C# - Fatal编程技术网

编写一个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文章和中的示例

有两种解决方案:

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

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

  • 另一件事是你可以用类来代替自己减去日期。这很简单:

    var span=DateTime.Now - dt;
    

    您从文本框名称txt_age1.Text中获取的输入是什么?我猜你是在记出生日期吧?