Sam Daniel
Sam Daniel

Reputation: 141

Remove Time from datetime field in dataset

Same question is available in stack but no answer. I have a dataset ds.Tables[0].Rows[0].Field<DateTime>("Date"))

I need to remove time from this field. Can anyone tell me how??? I tried the following but it did not work

Convert.ToDateTime(ds.Tables[0].Rows[0].Field<DateTime>("Date")).ToString("MM/dd/yyyy");

Upvotes: 2

Views: 1953

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460058

A DateTime alsways has a date and a time portion. It just has a value without any format. So you are confusing it with it's representation, for example if you call dt.ToString().

You achieve the same what you are doing above without converting it to string, applying a format that only shows the date and finally converting the result back to DateTime. You just need to use it's Date property

DateTime yourDateTime = ds.Tables[0].Rows[0].Field<DateTime>("Date");
DateTime onlyDate = yourDateTime.Date;

But, as said above, this will not remove the hours, minutes and seconds, they are just zeros now. Therefore you have to use one of these:

  1. string onlyDateDisplayed = yourDateTime.ToString("d");
  2. string onlyDateDisplayed = yourDateTime.ToString("MM/dd/yyyy");
  3. string onlyDateDisplayed = yourDateTime.ToShortDateString();

Upvotes: 4

Related Questions