解析具有单个数字日的日期字符串,例如1-11-2017以及12-11-2017

时间:2017-11-01 10:30:31

标签: c# datetime

所以我有一个日期字符串,其中包含今天的短日期。 例如" 1-11-2017"

//Here i convert the HttpCookie to a String 
string DateView = Convert.ToString(CurrDay.Value);

//Here i convert the String to DateTime
DateTime myDate = DateTime.ParseExact(DateView, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);

运行代码后,我收到错误:

  

用户代码

未对FormatExeption进行处理      

类型' System.FormatException'的例外情况发生在   mscorlib.dll但未在用户代码中处理

     

其他信息:字符串未被识别为有效的DateTime。

6 个答案:

答案 0 :(得分:6)

1-11-2017的格式不是dd-MM-yyyy,特别是第一部分。使用d-M-yyyy代替当值低于10时使用一位数的日期和月份(即没有0​​填充)。

测试:

DateTime myDate = DateTime.ParseExact("1-11-2017", "d-M-yyyy", System.Globalization.CultureInfo.InvariantCulture);
Console.WriteLine(myDate.ToString());

如果你不知道是否会有0个填充,你可以传递一组可接受的格式,解析器将尝试每个格式,以便它们出现在数组中。

DateTime myDate = DateTime.ParseExact("1-11-2017", new string[]{"d-M-yyyy", "dd-MM-yyyy"}, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);

Fiddle

答案 1 :(得分:1)

我用yyyy-MM-dd而不是dd-MM-yyyy解决了这个问题 (后来将其转换为正常日期) 因为变换总是当天的日子可以是1和2位

 CurrDay.Value = DateTime.Now.ToString("yyyy-MM-dd" ); 

 // Convert String to DateTime
 dateFrom = DateTime.ParseExact(CurrDay.Value.ToString(), "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);

以下评论帮助我找到了这个解决方案, 谢谢大家!

答案 2 :(得分:0)

这是因为ParseExact表示您传递格式,并且该方法需要将相同的日期格式作为字符串传递,这就是您需要传递d-MM-yyyy而不是dd-MM-yyyy的原因。

我不确定传递的字符串是否有一个或两个数字,然后执行以下操作:

string[] digits = DateView.split('-');
DateTime dateTime = new DateTime(digits[2], digits[1], digits[0]);

您甚至可以使用/进行拆分,但您需要确保第一个数字是一天,第二个数字是月份,依此类推。

我的建议是传递刻度而不是日期时间字符串:

DateTime date = new DateTime(numberOfTicks);
string valueAsStr = date.ToString("dd-mm-yyyy");

答案 3 :(得分:0)

日期格式dd代表The day of the month, from 01 through 31.您可以将其作为01-11-2017提供,也可以将格式化程序更改为d-MM-yyyy

以下是对Custom Date and Time Format Strings

的引用

答案 4 :(得分:0)

传递如下所示的值,

  string DateView = Convert.ToString("01-11-2017");
  DateTime myDate = DateTime.ParseExact(DateView, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);

答案 5 :(得分:0)

使用LINQ校正Dabass的方法(因为DateTime不能接受字符串)是

int[] digits = DateView.split('-').Select(int.Parse).ToArray();
DateTime dateTime = new DateTime(digits[2], digits[1], digits[0]);

由于