0

I tried to use

 sqlDr.GetValue(a).ToString() 

to display a DATE column from my database which looks like this..(the Date Submitted column) enter image description here

But the problem is , when i display it using getValue(8).toString(), something like this is displayed..

enter image description here

Thanks for taking your time to read my post , any reply is much appreciated!

6
  • change it to sqlDr.GetValue(a).ToString("yyyy-MM-dd") this should fix it. Commented Mar 2, 2018 at 20:20
  • The problem is i have many columns and not just date, does other column works too if i do that? Thanks Commented Mar 2, 2018 at 20:35
  • 1
    it works on DateTime columns only. so if the other columns matches the same datatype, it should works fine, the following link should give you a good overview learn.microsoft.com/en-us/dotnet/standard/base-types/… Commented Mar 2, 2018 at 20:38
  • @iSR5 Thanks, but i am getting another error after adding the line , (no overload for method 'ToString' Takes 1 arguments) Any Clue ? Commented Mar 2, 2018 at 20:43
  • perhaps your calling a nullable DateTime, review this post stackoverflow.com/questions/33371527/… Commented Mar 2, 2018 at 20:50

2 Answers 2

1

The problem is .Net does not have a Date-only primitive type. Therefore the Sql Server Date column type maps to a full DateTime value in .Net, which always includes a time component. If you don't provide a time component, the DateTime struct will have a 0-value time component, which maps to 12:00:00.000 AM.

To get around this, you need to specify the output format for your column, so that it explicitly does not include a time value. You want something like this:

 ((DateTime)getValue(8)).ToString("d")

However, the exact code you need will vary wildly depending on how your result table is created. If necessary, check the SqlDataReader.GetDataTypeName() function to know what type you're dealing with.

Sign up to request clarification or add additional context in comments.

2 Comments

but the problem is now i am currently displaying from dynamic table , as i would not know which value is date , my code is something like this currently. html += "<tr>"; for (int a = 0; a< (list.Count - 1); a++) { html += "<td>" + sqlDr.GetValue(a).ToString() + "</td>"; } html += "</tr>"; Thanks
Try using the SqlDataReader.GetDataTypeName() method to check the type so you can format it.
0

Try using the DateTime.ToShortTimeString Method ():

Console.WriteLine("Short date string:  \"{0}\"\n", myDateTime.ToShortDateString());

Output: Short date string: "5/16/2001"

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.