简体   繁体   中英

Changing DATETIME format in datatable column without using loop in C#

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?

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

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM