Reputation: 314
I have a Data Table that has a column 'subscribeDate' that has dates in MM/dd/yyyy hh:mm:ss format. I would like to change all the dates in this column to MM-dd-yyyy hh:mm:ss format. Is there a way that I can do it without running a loop?
Upvotes: 2
Views: 23365
Reputation: 62256
You should be able to do that, if there is not some culture restrictions in your app (I don't know how works your application) with convert method. Somethign like this:
myTable.Columns["Date"].Convert(
val => DateTime.Parse(val.ToString()).ToString("dd/MMM/yyyy"));
Where convert function you can find in Is it possible to format a date column of a datatable?
Upvotes: 3
Reputation: 1500595
I would hope that the values in the DataTable
are of type DateTime
or DateTimeOffset
.
Assuming that's the case, they don't have a format. They're just dates and times. How you convert them to a string is up to you.
If they're not already in an appropriate data type, you should try to change how you obtain the data to start with. Convert it from a string format to a more appropriate data type as early as you possibly can, and only convert it back to a string when you really need to.
You haven't explained how you're displaying the DataTable
, but most ways that I'm aware of allow you to specify a format string - that's where you would specify your MM-dd-yyyy HH:mm:ss
format. (Note HH
rather than hh
, to get 24 hours.)
Upvotes: 4