删除DateTime对象中的hours:seconds:毫秒 [英] Remove hours:seconds:milliseconds in DateTime object

查看:121
本文介绍了删除DateTime对象中的hours:seconds:毫秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从DateTime对象创建一个字符串,该字符串的格式为 mm:dd:yyyy

I'm trying to create a string from the DateTime object which yields the format mm:dd:yyyy.

通常, DateTime 对象是 mm:dd:yyyy hrs:min:sec上午/下午

是否可以快速删除DateTime的 hrs:min:sec AM / PM 部分,以便当我将其转换为 ToString()时,只会导致 mm:dd:yyyy

Is there a way to quickly remove the hrs:min:sec AM/PM portion of the DateTime so that when I convert it ToString() it will only result in mm:dd:yyyy?

推荐答案

要回答您的问题,不-您必须将其存储为其他类型。最简单的选择是使用字符串。

To answer your question, no - you would have to store it in a different type. The most simple choice is to use a string.

string date = dateTime.ToString("MM:dd:yyyy");

不过,我也强烈建议不要在程序内部将日期存储为字符串。这将使得很难对其进行任何计算或比较。此外,我建议您不要对日期表示法强加特定的文化,因为这意味着您的应用程序可能无法在您期望的其他文化中正常工作。

However I'd also strongly advise against storing dates internally in your program as strings. This will make it difficult to do any calculations or comparisons on them. Furthermore I'd advise you against forcing a specific culture for your date representation as it means your application probably won't work as expected in other cultures than yours.

稍微复杂一点的方法是创建一个覆盖ToString的自定义类。不过,我也避免这样做,因为使用标准库函数仍然很难使用您的类型。

A slightly more sophisticated approach is to create a custom class which overrides ToString. I'd also avoid this though, because it will still be difficult to use your type with the standard library functions. You will have to convert back and forth all the time.

只需将其保留为DateTime并仅在表示层将其转换为字符串即可。您可以使用 DateTime.ToShortDateString 打印用户友好的可识别文化的字符串。

Just leave it as a DateTime and do the conversion to string only in the presentation layer. You can use DateTime.ToShortDateStringto print a user friendly culture aware string.

这篇关于删除DateTime对象中的hours:seconds:毫秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆