tags:

views:

264

answers:

2

Hi I have noted that if I use TimespanObj.ToString() the it gives me perfect output like 12:33:00.

But I use following linq query.

var time = SomeSimpleQuery.Select(t => new { time = t.FromTime.ToString() });

where FromTime is time(7) in SQL Database and Timespan in LINQ-TO-SQL Class (by Default).

Then I get the output having format like "jan 1 1900 12:00PM". Why?

+1  A: 

I dont recall SQL having a timespan type. time would simply be the hour part of a day.

From MSDN (for time datatype):

Defines a time of a day. The time is without time zone awareness and is based on a 24-hour clock.

leppie
I use MS SQL2008 and FromTime is type of Time(7). Then I use LINQ-to-SQL Class and FromTime will be type of Timespan.
Vikas
+1  A: 

I suspect it's because the "ToString" part of your query is being performed in SQL rather than in .NET. You should be able to confirm this by checking the SQL which is being executed.

Try fetching the FromTime property directly and then call ToString() on the result instead. You can force processing to be performed at the .NET side using AsEnumerable if you want to keep it all in a LINQ query:

var time = SomeSimpleQuery.Select(t => t.FromTime)
                          .AsEnumerable()
                          .Select(t => new { time = t.ToString() });

If you want to fetch other things, just pass those through:

var query = SomeSimpleQuery.Select(row => new { UserId=row.UserId,
                                                Query=row.Query,
                                                Time=t.FromTime })
                           .AsEnumerable()
                           .Select(t => new { t.UserId, t.Query,
                                              Time=t.FromTime.ToString() });
Jon Skeet
Good! Can I Convert It at SQL side? Because I am also fetching other Inforamations. Not just Time.
Vikas
Fetch all the rest of the information at the same time, but just do the ToString processing back at the client side, leaving all the rest of the data the same. I don't know how you'd go about formatting it in the SQL side, especially from LINQ. I'll edit the answer to show what I mean.
Jon Skeet