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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13579276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:04:07  来源:igfitidea点击:

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

c#datetimedatatable

提问by Huzaifa Qamer

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?

我有一个数据表,其中有一列“subscribeDate”,该列的日期为 MM/dd/yyyy hh:mm:ss 格式。我想将此列中的所有日期更改为 MM-dd-yyyy hh:mm:ss 格式。有没有一种方法可以在不运行循环的情况下做到这一点?

采纳答案by Jon Skeet

I would hope that the values in the DataTableare of type DateTimeor DateTimeOffset. Assuming that's the case, they don't havea format. They're just dates and times. How you convert them to a string is up to you.

我希望 中的值DataTable是类型DateTimeor DateTimeOffset。假设是这样的话,他们不具备的格式。它们只是日期和时间。如何将它们转换为字符串取决于您。

If they're notalready 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 backto 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'swhere you would specify your MM-dd-yyyy HH:mm:ssformat. (Note HHrather than hh, to get 24 hours.)

您还没有解释如何显示DataTable,但我所知道的大多数方法都允许您指定格式字符串 -就是您指定MM-dd-yyyy HH:mm:ss格式的地方。(注意HH而不是hh, 以获得 24 小时。)

回答by Tigran

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:

如果您的应用程序中没有一些文化限制(我不知道您的应用程序如何工作),您应该能够使用 convert 方法。像这样的东西:

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?

您可以在哪里找到转换函数是否可以格式化数据表的日期列?