tags:

views:

44

answers:

4

i have the following code but it does not work to comapre a date converted form string can any body help me on this thanks in advance

        DateTime dt = DateTime.Now;
        List<DateTime> dateTimes = new List<DateTime>();
        dateTimes.Add(dt);
        dateTimes.Add(dt);
        dateTimes.Add(dt);
        string str = dt.ToString();
        DateTime myDateTime = DateTime.Parse(str);

        var query = from d in dateTimes
                    where d == myDateTime
                    select d;
        foreach (var result in query)
        {
            Console.WriteLine(result);
        }
        Console.Read();
+1  A: 

The reason is that the ToString method is truncating the actual time slightly, so the result isn't the same when you go back in the other direction.

Replace your first line, for example, with

DateTime dt = new DateTime(2009,10,29,16,35,56);

and you'll see what's going on.

FinnNk
A: 

Hi,

I would recommend not to use ToString() so frequently when you need to switch between types, the better way is to use custom object to at least specialized versions of methods for comparison like CompareTo.

try This

DateTime dt = DateTime.Now; List dateTimes = new List(); dateTimes.Add(dt); dateTimes.Add(dt); dateTimes.Add(dt); string str = dt.ToString(); DateTime myDateTime = DateTime.Parse(str);

    var query = from d in dateTimes
                where d.CompareTo(myDateTime) == 1
                select d;
    foreach (var result in query)
    {
        Console.WriteLine(result);
    }
    Console.Read();

Regards,

Usman Afzal

Usman Afzal
A: 

Hi, But my scenario is little bit change i assign a attribute to the view linkbutton in asp.net and when user click on the view link button i get the attribute from the linkbutton and and cast that to datetime object than i want to get data from table using linq query so i need the conversion from string to datetime can anybody figure out why it is not campare in the linq query thanks in advance

RAHAT ALI
A: 

Hi To all i have solved the problem solution is not to save the timestamp in datetime format in string insetead you should convert datetime object to its corrsponding ticks and store that ticks in the string variable and after word when you want to make the date object use the following line of code DateTime myDateTime = new DateTime(int64.Parse(strDateTimeTicks)); this will returned the exact datetime object

RAHAT ALI