0

I am trying to format a date. I get the date from the database in the dateTime format and i want to show only the date part not the time.

 string date = dt.Rows[0]["declaration_date"].ToString();
 string dateFormat = date.ToString("MM/DD/YYYY");

This is not working. Any help?

3
  • DateTime date = (DateTime) dt.Rows[0]["declaration_date"]; Commented Aug 1, 2018 at 7:47
  • If declaration_date is a DateTime column you should not convert it to a string. DateTime result = dt.Rows[0].Field<DateTime>("declaration_date"); Commented Aug 1, 2018 at 7:47
  • Your date is already a string, you used 'ToString()' on it already. Commented Aug 1, 2018 at 7:47

2 Answers 2

2

For date.ToString with formatting to work, date needs to be a DateTime. Try changing your code to something like this:

 DateTime date = (DateTime)dt.Rows[0]["declaration_date"];
 string dateFormat = date.ToString("MM/dd/yyyy");

Also, your formatting string should be MM/dd/yyyy.

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

Comments

0

You are doing it almost correctly.

Try this:

string date = dt.Rows[0]["declaration_date"].ToString("MM/dd/yyyy");

The point is that you have to apply .ToString("MM/dd/yy") to a DateTime object, not to a string.

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.