2

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?

Huzaifa Qamer
  • 314
  • 2
  • 4
  • 17

2 Answers2

4

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.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3

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?

Community
  • 1
  • 1
Tigran
  • 61,654
  • 8
  • 86
  • 123