Rashmi Pandit
Rashmi Pandit

Reputation: 23868

Converting DateTime data to String in dataset

I have a dataset which stores dates in a DataColumn (datatype of this column is DateTime). I need to change the format from DateTime to string that will give me the date as per my current culture.

In case of a single DateTime variable, I can use the overloaded ToString() to achieve this in the following manner:

DateTime.Now.ToString(System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern)

But I need to convert data for all the rows in my DataSet to string. Does anyone have an idea on how I can achieve this?

Thanks.

Upvotes: 1

Views: 4412

Answers (5)

Cerebrus
Cerebrus

Reputation: 25775

If I were you, I would keep the data in the DataTable as it is. It is after all, meaningful data that would lose its meaning upon conversion. I would make any desired modifications only when displaying/rendering the data because that implicitly requires a conversion of the data into strings (with optional formatting).

Any DateTime variable can be rendered as a string (with culture-sensitive formatting) using the simple code:

DateTime.Now.ToShortDateString();
// Or
DateTime.Now.ToString("d");

This function already uses formatting information derived from the current culture.

I really would suggest that you take another look at your scenario to evaluate if you really need to change the datatype of data in the dataset itself. (or provide us with more information)

Upvotes: 0

sabiland
sabiland

Reputation: 2614

When you get the DataSet:

  • locate apropriate DataTable
  • add new DataColumn
  • in one loop you populate new Column with (your DateTime).ToString()

Upvotes: 5

Sergio
Sergio

Reputation: 8269

New answer :)

I have been googling an came up with this site: Linq to Dataset

That example shows how you can use linq on a dataset, I am guessing that you could use a query to perform the data transformation and place it on the new datatable. Not sure if it will perform better then the loop

Upvotes: 0

Sergio
Sergio

Reputation: 8269

I don't think it's possible to change a column type after the table been filled. I think you should create a second table on your dataset and copy the information you need transforming the date in the process.

Upvotes: 0

abmv
abmv

Reputation: 7118

  1. Get the Dataset.
  2. for each row convert to string and put it in new dataset (along with rest of data).

Upvotes: 1

Related Questions