C# 字符串未被识别为有效的DateTime:格式异常
我有这样的路径…“C:\restore\restoredb\” 在那条路径中,我有这样的文件C# 字符串未被识别为有效的DateTime:格式异常,c#,.net,winforms,string,datetime,C#,.net,Winforms,String,Datetime,我有这样的路径…“C:\restore\restoredb\” 在那条路径中,我有这样的文件 backup-2011-10-12T17-16-51.zip backup-2011-10-11T13-24-45.zip 我有一个表单,在这个表单中我有一个列表框和组合框(cbrestore),我有这样的组合框项目…月,3个月,6个月,年 我想要的是,如果我选择组合框项目(月),我想显示在这些日期(2011年10月12日至2011年9月12日)之间存储在该文件夹中的文件名 如果我选择组合框项目(
backup-2011-10-12T17-16-51.zip
backup-2011-10-11T13-24-45.zip
我有一个表单,在这个表单中我有一个列表框和组合框(cbrestore),我有这样的组合框项目…月,3个月,6个月,年
我想要的是,如果我选择组合框项目(月),我想显示在这些日期(2011年10月12日至2011年9月12日)之间存储在该文件夹中的文件名
如果我选择组合框项目(3个月),我希望在列表框中显示这些日期(2011年10月12日至2011年7月12日)之间存储在该文件夹中的文件名
为此,我尝试了这个…但是,如果我选择了组合框项目月,那么我得到了下面提到的错误
List<String> t = Directory.GetFiles(@"C:\restore\restoredb\").ToList();
List<String> y = new List<string>();
List<String> u = new List<string>();
foreach (var zzz in t)
{
y.Add(Path.GetFileName(zzz));
}
if (comboBox1.Text == "Month")
{
u =
(from String s in y where ((DateTime.Now.Month - DateTime.Parse(s.Substring(8, 10)).Month) < 1) && (DateTime.Now.Year - DateTime.Parse(s.Substring(8, 10)).Year == 0) select s).
ToList();
}
List t=Directory.GetFiles(@“C:\restore\restoredb\”).ToList();
列表y=新列表();
列表u=新列表();
foreach(t中的变量zzz)
{
y、 添加(Path.GetFileName(zzz));
}
如果(comboBox1.Text==“月”)
{
u=
(来自y中的字符串s,其中((DateTime.Now.Month-DateTime.Parse(s.Substring(8,10)).Month)<1)和&(DateTime.Now.Year-DateTime.Parse(s.Substring(8,10)).Year==0)选择s)。
托利斯特();
}
错误:未处理格式异常,字符串未被识别为有效的日期时间
在这条线上
(DateTime.Now.Month - (DateTime.Parse(s.Substring(8, 10)).Month) < 1) && (DateTime.Now.Year - DateTime.Parse(s.Substring(8, 10)).Year == 0)
(DateTime.Now.Month-(DateTime.Parse(s.Substring(8,10)).Month)<1&(DateTime.Now.Year-DateTime.Parse(s.Substring(8,10)).Year==0)
在这件事上,请帮忙好吗
非常感谢……我想你在索引中犯了一个错误
请尝试使用s.Substring(7,10)。我认为您在索引中犯了一个错误
请尝试使用s.Substring(7,10)。在我看来,您的索引不正确。您正在服用011-10-12T
s、 子字符串(7,10)在我看来,您的索引不正确。您正在服用011-10-12T s、 子字符串(7,10)s。子字符串(8,10)是基于您的输入的字符串“011-10-12T”,不会被解析为日期或日期的一部分 尝试从inputstring构造日期时间,如:
string input = "backup-2011-10-12T17-16-51.zip";
string[] splitInputs = input.Split('-');
DateTime inputDate = new DateTime(
int.Parse(splitInputs[1]), //Year
int.Parse(splitInputs[2]), //Month
int.Parse(splitInputs[3].Split('T')[0]), //Day left of the T
int.Parse(splitInputs[3].Split('T')[1]), //Hour, right of the T
int.Parse(splitInputs[4]), //Minutes
int.Parse(splitInputs[5].Split('.')[0])); //Seconds, left of the .zip
并使用该构造的日期时间进行比较 s.Substring(8,10)是基于您的输入的字符串“011-10-12T”,它不会被解析为日期或日期的一部分
尝试从inputstring构造日期时间,如:
string input = "backup-2011-10-12T17-16-51.zip";
string[] splitInputs = input.Split('-');
DateTime inputDate = new DateTime(
int.Parse(splitInputs[1]), //Year
int.Parse(splitInputs[2]), //Month
int.Parse(splitInputs[3].Split('T')[0]), //Day left of the T
int.Parse(splitInputs[3].Split('T')[1]), //Hour, right of the T
int.Parse(splitInputs[4]), //Minutes
int.Parse(splitInputs[5].Split('.')[0])); //Seconds, left of the .zip
并使用该构造的日期时间进行比较