是否可以格式化数据表的日期列?
考虑我有一个数据表dt
,它有一列DateofOrder
,
DateofOrder
07/01/2010
07/05/2010
07/06/2010
我想将DateOfOrder
列中的这些日期格式化为这个
DateofOrder
01/Jul/2010
05/Jul/2010
06/Jul/2010
任何建议。
Consider i have a datatable dt
and it has a column DateofOrder
,
DateofOrder
07/01/2010
07/05/2010
07/06/2010
I want to format these dates in DateOfOrder
column to this
DateofOrder
01/Jul/2010
05/Jul/2010
06/Jul/2010
Any suggestion..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
最明智的做法是确保您的 DataTable 已键入,并且此列的类型为 DateTime。然后,当您实际将值打印到屏幕上时,您可以在此时设置格式,而无需修改底层数据。
如果这不可行,这里有一个我经常使用的扩展方法:
您可以在您的情况下使用,例如:
它仅适用于非类型化数据表(例如,列类型必须是对象,或者可能是字符串)。
The smartest thing to do would be to make sure your DataTable is typed, and this column is of type DateTime. Then when you go to actually print the values to the screen, you can set the format at that point without mucking with the underlying data.
If that's not feasible, here's an extension method I use often:
You could use in your situation like:
It only works on untyped DataTables (e.g. the column type needs to be object, or possibly string).
.ToString("dd/MMM/yyyy")
(假设你的数据是DateTime类型)
.ToString("dd/MMM/yyyy")
(assuming your data is DateTime type)
只是在这里阐述 saille 的答案:
对于 DateTime,格式不是问题。 DateTime 实际上是从公元 1 月 1 日午夜开始计算的刻度数。所以,实际上,它只是一个 long。仅当将其转换为字符串时,格式化才成为问题。因此,当您将其从数据表中取出并准备输出时,或者将其作为字符串放入数据表中时,您必须处理格式化(为了灵活性,我不建议这样做)目的)。格式化可以通过 saille 建议的 DateTime 上的 .ToString 调用来完成,
.ToString("dd/MMM/yyyy")
Just expounding on saille's answer here:
For a DateTime, format isn't an issue. A DateTime is actually the number of ticks counting up from midnight, January 1, 1 A.D. So, really, it's just a long. Formatting only becomes an issue when it comes time to convert it into a string. So, you'll have to go and take care of the formatting either when you pull it out of the data table and are ready to output it, or put it into the data table as a string (which I would not recommend, for flexibility purposes). The formatting can be done with the .ToString call on the DateTime that saille suggests,
.ToString("dd/MMM/yyyy")
只是补充一下,您需要将扩展方法放入
.cs
文件中,通常是某种Utility.cs
,然后在的帮助下访问该文件>using
语句。此处提供了完整的示例: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods
Just to add, you need to put your extension method to a
.cs
file usually some sort of aUtility.cs
and then get access to that with the help ofusing
statement.A complete example is provided here: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods