C# 用户代码未处理日期时间格式异常

C# 用户代码未处理日期时间格式异常,c#,datetime,formatexception,C#,Datetime,Formatexception,这是一个C#web服务,我正在努力使其正确 arg1是一个下拉菜单,用户可以从中选择年度、月度和季度。 arg2是他们输入的日期。 arg3是他们选择的日期加上一年、一个月或三个月 到目前为止,我已经整理好了: public ServiceResult CallService(string arg1, string arg2 = "", string arg3 = "") { System.Threading.Thread.CurrentThre

这是一个
C#
web服务,我正在努力使其正确

arg1
是一个下拉菜单,用户可以从中选择年度、月度和季度。
arg2
是他们输入的日期。
arg3
是他们选择的日期加上一年、一个月或三个月

到目前为止,我已经整理好了:

public ServiceResult CallService(string arg1, string arg2 = "", string arg3 = "")
{
     System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");

     //Write Your Code Here
     if (arg1 == "1 - Annually")
     {
                
         DateTime thisDate1 = Convert.ToDateTime(arg2);
         thisDate1.AddYears(1);
         arg3 = Convert.ToString(thisDate1);
                
     }

     return new EchoInputHandler().EchoInput(arg1, arg2, arg3);
}
FormatException was unhandled by user Code
An Exception of type 'System.FormatException' occurred in mscor.lib but was not handled in user code
Additional information: String was not recognized as a valid DateTime.
我收到一个错误:

public ServiceResult CallService(string arg1, string arg2 = "", string arg3 = "")
{
     System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");

     //Write Your Code Here
     if (arg1 == "1 - Annually")
     {
                
         DateTime thisDate1 = Convert.ToDateTime(arg2);
         thisDate1.AddYears(1);
         arg3 = Convert.ToString(thisDate1);
                
     }

     return new EchoInputHandler().EchoInput(arg1, arg2, arg3);
}
FormatException was unhandled by user Code
An Exception of type 'System.FormatException' occurred in mscor.lib but was not handled in user code
Additional information: String was not recognized as a valid DateTime.
有人能告诉我为什么会这样吗


解决了的 我已经解决了!这就是我的代码现在的样子:

public ServiceResult CallService(string arg1, string arg2 = "", string arg3 = "")

    {
        if (arg1 == "1 - Annually")
        {
            DateTime arg2Date = Convert.ToDateTime(arg2);
            arg2Date = arg2Date.AddYears(1);
            arg3 = arg2Date.ToString("dd/MM/yyyy");
        }
     }

基本上,它告诉您Arg2不能被识别为有效的日期时间

我将做一些增强:

1) 确保不要在空字符串上调用Convert.ToDateTime(请改用.Parse,基本上这是Convert.ToDateTime内部使用的)

2) 确保验证arg2-您应该知道输入格式

3) 如果你知道输入格式。使用ParseExact


4) 确保在try/catch处理中使用.Parse og.ParseExact,并在catch异常中返回一些对客户端有用的内容

尝试使用DateTime.ParseExact并应用您尝试使用的日期格式。

arg2的值是什么错误非常清楚。
arg2
中的任何内容都不会被识别为
DateTime
格式。所以arg2的值是一个日期,可以是今天,也可以是他们选择的任何一天。例如2015年8月19日。天/月/年收到此错误时arg2的确切值是多少?@ChristophBethge:
“可以是今天,也可以是他们选择的任何一天”
。。。好的,当抛出错误时是什么?不是它可能是什么或应该是什么,而是它到底是什么?不要猜测或假设,调试。