简体   繁体   English

更改数据表列中的DATETIME格式而不在C#中使用循环

[英]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. 我有一个数据表,其中的列“ subscribeDate”具有MM / dd / yyyy hh:mm:ss格式的日期。 I would like to change all the dates in this column to MM-dd-yyyy hh:mm:ss format. 我想将此列中的所有日期更改为MM-dd-yyyy hh:mm:ss格式。 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 . 我希望DataTable中的值是DateTimeDateTimeOffset类型。 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. 你没有解释你是如何显示的DataTable ,但据我所知,您可以指定格式字符串的很多方面- 这就是你会指定MM-dd-yyyy HH:mm:ss格式。 (Note HH rather than hh , to get 24 hours.) (注意HH而不是hh ,以获得24小时。)

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. 如果您的应用程序中没有使用convert方法的文化限制(我不知道您的应用程序如何工作),那么您应该能够做到这一点。 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? 您可以找到转换函数的位置是否可以格式化数据表的日期列?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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