是否有一种文化安全的方法来获取带有前导零的 ToShortDateString() 和 ToShortTimeString() ?
我知道我可以使用格式字符串,但我不想丢失日期/时间格式的文化特定表示。例如
5/4/2011 |下午 2:06 | ...
应该是 05/04/2011 |下午 02:06 | ...
但是当我将其更改为不同的文化时,我希望它是
04.05.2011 | 14:06 | 14:06 ...
而不更改格式字符串。这可能吗?
I know that I could use a format string, but I don't want to lose the culture specific representation of the date/time format. E.g.
5/4/2011 | 2:06 PM | ...
should be 05/04/2011 | 02:06 PM | ...
But when I change it to a different culture, I want it to be
04.05.2011 | 14:06 | ...
without changing the format string. Is that possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用
DateTimeFormatInfo.CurrentInfo
ShortDatePattern
和ShortTimePattern
进行翻译:You can use the
DateTimeFormatInfo.CurrentInfo
ShortDatePattern
andShortTimePattern
to do the translation:这里的答案非常复杂。实际上,它就像简单一样
有关所有格式的完整列表以及示例输出,请参阅 https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tostring?view=net-5.0。
Really complicated answers here. In reality it's as simple as
For a full list of all formats with example outputs see https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tostring?view=net-5.0.
我只看到一个解决方案 - 您应该获取当前的区域性显示格式,对其进行修补,使其满足您的要求,最后使用修补后的格式字符串格式化您的 DateTime 值。这是一些示例代码:
正如所承诺的,这里是改进的版本:
I see only a single solution - you should obtain the current culture display format, patch it so that it meets your requirement and finally format your DateTime value using the patched format string. Here is some sample code:
As promised, here is the improved version:
您还可以重写 CurrentThread.CurrentCulture 类。在程序的开头,您可以调用此方法:
通过此方法,您在程序中将日期显示为字符串的任何位置都将具有新的格式。
You could also override the CurrentThread.CurrentCulture class. At the beginning of your program you call this method:
With this, anywhere you display a date as a string in your program it will have the new format.
我写了一个方法来进行这种转换:
调用它,用于时间格式:
希望它可以帮助你
I wrote a method to do that kind of transformations :
To call it, for time format :
Hope it can help u