开发者

String was not recognized as a valid DateTime: Format exception

开发者 https://www.devze.com 2023-04-12 22:25 出处:网络
I have path like this...\"C:\\restore\\restoredb\\\" In that path i have files like this.. backup-2011-10-12T17-16-51.zip

I have path like this..."C:\restore\restoredb\"

In that path i have files like this..

 backup-2011-10-12T17-16-51.zip
 backup-2011-10-11T13-24-45.zip

I have a form , in that form i have a listbox and combobox(cbrestore) I have got the combobox items like this ...Month, 3 months,6 months,year...

what i want is , if i select the combobox item(month) i want to display the file names which are stored in that folder between these dates (12-10-2011 to 12-09-2011)..

If i select combobox item(3 months) i want to display the file names which are stored in that folder between these dates (12-10-2011 to 12-07-2011)..in listbox

For that i have tried this ....but, if i select combo box item month then i got the error like i mentioned below

 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();
    }

Error: Format Exception was unhandled , String was not recognized as a valid DateTime.

at this line

(DateTime.Now.Mont开发者_JAVA百科h - (DateTime.Parse(s.Substring(8, 10)).Month) < 1) && (DateTime.Now.Year - DateTime.Parse(s.Substring(8, 10)).Year == 0)

would any pls help on this......

Many thanks.....


I think you've made a mistake in indexes.

Try s.Substring(7, 10) instead.


It seems to me your index is not correct. You are taking 011-10-12T

s.Substring(7, 10)


s.Substring(8, 10) is the string "011-10-12T" based on your inputs, that won't be parsed as a date or a portion of a date.

Try to construct a datetime from the inputstring, like:

 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

And use that constreucted DateTime to perform your comparisons.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号