2

I have the following code,and I am trying to compare The date string with date time,but I can't get it to work.This does not output any rows.

DataTable tbl3 = dii.SelectGeneric("select * from widget_messages  where convert(datetime, m_date) ='" + String.Format("{0:d/M/yyyy}", DateUsed) + "'");

Both datetimes are formatted exactly the same.Any ideas?

3
  • What happens when you run the exact query into the database yourself? Commented Sep 8, 2012 at 23:15
  • 3
    the best fromat for sql 'yyyy-MM-dd' Commented Sep 8, 2012 at 23:16
  • @Arran - I've run the query with the date instead of DateUsed,but i still get no results. Commented Sep 9, 2012 at 9:56

2 Answers 2

2

You are converting the m_date to datetime but DateUsed remains a string.

You should either compare them as strings, like this

DataTable tbl3 = dii.SelectGeneric("select * from widget_messages  where m_date ='" + String.Format("{0:d/M/yyyy}", DateUsed) + "'");

or as datetimes, like this:

DataTable tbl3 = dii.SelectGeneric("select * from widget_messages  where convert(datetime, m_date) = convert(datetime,'" + String.Format("{0:d/M/yyyy}", DateUsed) + "')");

EDIT: On SQL Server 2005 try this:

DataTable tbl3 = dii.SelectGeneric("select * from widget_messages  where abs(datediff(day,convert(datetime, m_date), convert(datetime,'" + String.Format("{0:d/M/yyyy}", DateUsed) + "'))) = 0");
Sign up to request clarification or add additional context in comments.

7 Comments

Thank you, @dasblinkenlight,still no results.I print out the date from database and the date from date used,and they are the same,but still no results.
@user1657214 Since you are using only the date portion, try converting to date rather than to datetime, like this: DataTable tbl3 = dii.SelectGeneric("select * from widget_messages where convert(date, m_date) = convert(date,'" + String.Format("{0:d/M/yyyy}", DateUsed) + "')");
Just tried than but i get this: Type date is not a defined system type
yep,that seems to be the case.
@user1657214 See the edit, datediff should work for sql server 2005.
|
0

If m_date field is Date/DateTime type then following code will work fine.

DataTable tbl3 = dii.SelectGeneric("select * from widget_messages  where convert(varchar, m_date, 12) ='" + String.Format("{0:yyyyMMdd}", DateUsed) + "'");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.