Solved

How do I trim a datetime value to just its date value in LINQ?

Posted on 2009-05-18
14
583 Views
Last Modified: 2013-11-11
I have created a c# website using visual studio 2008. I am using the asp.net 3.5 listview control as a frontend to my backend sql server 2005 database. I am using a linq data source (linq to sql) to bind my listview to my backend database. Within the OnSelecting event of my linq data source I have written the attached query which works fine in regards to datetime values that do not allow nulls in my database but unfortunately it was necessary for me to allow nulls in one of my datetime fields (StopDate) which has invertingly not allowed me to reference "ToShortDateString" for that field in my linq query? Is there a way around this at all?
var query = from ptp in db.TrustPayments

                    join ppfl in db.PaymentFrequencyLookups on ptp.FrequencyCode equals ppfl.FrequencyCode

                    join tt in db.Trusts on ptp.TrustID equals tt.TrustID

                    select new { ptp.PaymentID, ptp.TrustID, StopDate = ptp.StopDate.ToShortDateString(), tt.ClientName, tt.MatterNo, ptp.SWDeptAccountNo, ptp.FrequencyCode, ptp.Amount, ptp.PayeeName, ptp.PayeeAddress, ptp.BankName, ptp.BankAddress, ptp.AccountName, ptp.AccountNo, ptp.SortCode, ptp.PaymentNotes, ptp.Archive };

Open in new window

0
Comment
Question by:Shepwedd
  • 6
  • 4
  • 2
  • +1
14 Comments
 
LVL 16

Expert Comment

by:ToddBeaulieu
Comment Utility
I wonder if you can just use inline "if" syntax:

StopDate = (ptp.StopDate != null) ? ptp.StopDate.ToShortDateString() : null
0
 

Author Comment

by:Shepwedd
Comment Utility
After trying your suggested code I noticed that Intelisense didn't offer me "ToShortDateString()" and when I do type it in I get the error: "System.Nullable<System.DateTime>" does not contain a definition for "ToShortDateString" ...?
0
 
LVL 16

Expert Comment

by:ToddBeaulieu
Comment Utility
Interesting. So you need to cast it. I tried this snippet and it works with and w/o a date.

System.DateTime? date = null;//System.DateTime.Now;
Console.WriteLine((date != null) ? ((DateTime)date).ToShortDateString() : "");
0
 
LVL 62

Expert Comment

by:Fernando Soto
Comment Utility
Hi Shepwedd;

Use a conditional if statement to test for null and take the proper action. See code snippet.

Fernando
var query = from ptp in db.TrustPayments

            join ppfl in db.PaymentFrequencyLookups on ptp.FrequencyCode equals ppfl.FrequencyCode

            join tt in db.Trusts on ptp.TrustID equals tt.TrustID

            select new { ptp.PaymentID, 

                         ptp.TrustID, 

                         StopDate = if (ptp.StopDate != null) ? ptp.StopDate.ToShortDateString() : String.Empty ,

                         tt.ClientName, 

                         tt.MatterNo, 

                         ptp.SWDeptAccountNo, 

                         ptp.FrequencyCode, 

                         ptp.Amount, 

                         ptp.PayeeName, 

                         ptp.PayeeAddress, 

                         ptp.BankName, 

                         ptp.BankAddress, 

                         ptp.AccountName, 

                         ptp.AccountNo, 

                         ptp.SortCode, 

                         ptp.PaymentNotes, 

                         ptp.Archive };

            

Open in new window

0
 
LVL 16

Expert Comment

by:ToddBeaulieu
Comment Utility
We went through that attempt. See my first response. My second post should solve the problem.
0
 
LVL 62

Expert Comment

by:Fernando Soto
Comment Utility
The 1st attempt seems to be missing the keyword "if"
0
 
LVL 62

Expert Comment

by:Fernando Soto
Comment Utility
@ ToddBeaulieu; My bad "if" not part of the conditional if statement.
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 62

Accepted Solution

by:
Fernando Soto earned 500 total points
Comment Utility
Hi Shepwedd;

This version of the query will do what you need.

Fernando
var query = from ptp in db.TrustPayments

            join ppfl in db.PaymentFrequencyLookups on ptp.FrequencyCode equals ppfl.FrequencyCode

            join tt in db.Trusts on ptp.TrustID equals tt.TrustID

            let Date = (ptp.StopDate.Value != null) ? ptp.StopDate.Value.ToShortDateString() : String.Empty

            select new { ptp.PaymentID, 

                         ptp.TrustID, 

                         StopDate = Date ,

                         tt.ClientName, 

                         tt.MatterNo, 

                         ptp.SWDeptAccountNo, 

                         ptp.FrequencyCode, 

                         ptp.Amount, 

                         ptp.PayeeName, 

                         ptp.PayeeAddress, 

                         ptp.BankName, 

                         ptp.BankAddress, 

                         ptp.AccountName, 

                         ptp.AccountNo, 

                         ptp.SortCode, 

                         ptp.PaymentNotes, 

                         ptp.Archive 

                       };

Open in new window

0
 
LVL 9

Expert Comment

by:Sreedhar Vengala
Comment Utility
The problem, though, is that SQL Server has no concept of DateTime.ToShortDateString, so the conversion to SQL fails
As FernandoSoto his query works fine.
Also you can do by:
Eg:
 

var list = (from p in Products           select p.SellEndDate).ToList();// calling ToList() above means we have the entire resultset in memory and// no longer have to pass the query back to SQL Servervar stuff = from p in list select new{     selldate = p.SellEndDate == null ?                   string.Empty :                   p.SellEndDate.Value.ToShortDateString()};

Open in new window

0
 
LVL 9

Expert Comment

by:Sreedhar Vengala
Comment Utility
var list = (from p in Products
           select p.SellEndDate).ToList();

// calling ToList() above means we have the entire resultset in memory and
// no longer have to pass the query back to SQL Server

var stuff = from p in list select new
{
    selldate = p.SellEndDate == null ?
                   string.Empty :
                   p.SellEndDate.Value.ToShortDateString()
};
0
 

Author Closing Comment

by:Shepwedd
Comment Utility
Excelllent, this worked a treat! Just for reference though, your initial code suggestion that included the "if" didn't work.
0
 
LVL 62

Expert Comment

by:Fernando Soto
Comment Utility
To your statement, "your initial code suggestion that included the "if" didn't work.", correct as I stated that on post 05/18/09 11:11 PM, ID: 24418184, Writing code in both C# and VB .Net, the syntax gets blured sometimes.
0
 
LVL 16

Expert Comment

by:ToddBeaulieu
Comment Utility
what i found most interesting was that the final solution was exactly the same as the solution i posted 5 entries prior! no biggie, i see a lot of that here.
0
 
LVL 62

Expert Comment

by:Fernando Soto
Comment Utility
@ ToddBeaulieu;

Not exactly the same. Please note that first I set a range variable called Date to the conditional if statement outside the Select clause once that is done I use that range variable in the Select clause. The compiler has issues with translating the query to T-SQL when done the other way around

This line was added to the query:
let Date = (ptp.StopDate.Value != null) ? ptp.StopDate.Value.ToShortDateString() : String.Empty
This line uses the result of the above line:
StopDate = Date ,

Which is not the same as:
StopDate = (ptp.StopDate != null) ? ptp.StopDate.ToShortDateString() : null

Fernando
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now