c# - 如何将 DateTime 转换为具有本地化小数秒的字符串?

标签 c# localization globalization

我有一个 DateTime 对象,我想将小时、分钟、秒和小数秒输出为针对当前区域性本地化的字符串。

这有两个问题。

第一个问题是没有标准的 DateTime 格式可以显示小数秒。我基本上想知道如何获得 long time日期时间格式,但带有小数秒。

我当然可以获取 DateTimeFormatInfo.LongTimePattern 并将“.fff”附加到它,然后将其传递给 DateTime.ToString(),但是某些特定于文化的格式,特别是美国,以 AM/PM 结尾。所以事情没那么简单。

第二个问题是 DateTime.ToString() 似乎没有本地化数字小数点分隔符。如果我决定只强制每种文化使用硬编码的自定义时间格式,它仍然不会创建本地化字符串,因为数字小数点分隔符不是特定于文化的。

使事情进一步复杂化的是,某些文化的日期时间格式使用句点作为其格式的一部分。这使得放置占位符(例如句点)并将其替换为特定于文化的小数点分隔符变得困难。

现在我已经采用了这个解决方法:

string format = string.Format("HH:mm:ss{0}fff",
    CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
string time = DateTime.Now.ToString(format);

我认为这应该适用于不具有与时间分隔符相同的小数点分隔符的所有文化,但这是一个假设。

注意:虽然对这两个问题都有解决方案会很好,但对于我的特定应用程序,与使用标准日期时间格式相比,我更感兴趣的是使用小数秒来本地化自定义日期时间格式。

最佳答案

First issue is there is no standard DateTime format that will show the fractional seconds. I essentially want to know how to get the long time DateTime format but with fractional seconds.

您可以考虑采用长格式,只需将“:ss”替换为“:ss.fff”,可能使用特定于文化的小数点分隔符:

string longPattern = culture.DateTimeFormat.LongTimePattern;
if (!longPattern.Contains(":ss"))
{
    // ???? Throw an exception? Test this with all system cultures, but be aware
    // that you might see custom ones...
}
// Only do it if the long pattern doesn't already contain .fff... although if
// it does, you might want to replace it using the culture's decimal separator...
if (!longPattern.Contains(".fff"))
{
    longPattern = longPattern.Replace(":ss", 
        ":ss" + culture.NumberFormat.DecimalSeparator + "fff");
}
string timeText = time.ToString(longPattern, culture);

To complicate matters further, some cultures have date time formats that use periods as part of their formatting. This makes it difficult to put a placeholder, for example the period and replace it with a culture specific decimal separator. Other than that though, it should end up putting the value in the right place. Do you definitely always want three digits though, even if the value is an exact second (or half a second, etc)? Use .FFF if not.

我怀疑这就是为什么没有使用文化特定的小数点分隔符。我自己也觉得很奇怪——事实上,我做了 Noda Time行为方式相同,即使我是 not convinced it's right .

最终,很多像这样的问题从根本上是有问题的:如果一种文化没有固定的方式来表示“带小数秒的时间”而你来表示小数秒,那么您将能够做的最好的事情就是有点拼凑。

关于c# - 如何将 DateTime 转换为具有本地化小数秒的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9794656/

相关文章:

c# - NHibernate - 删除时将外键列设置为空

c# - .NET 字符串哈希函数是否可移植?

c# - Blazor 服务器端 : How can I read out the local time of the user/browser not of the server (using only c#)

templates - 使用 require.js、主干和下划线本地化模板

jquery - 在 JQuery 中获取本地化语言

asp.net-mvc-3 - 是否可以为DataType为DataType.Currency的MVC3字段强制使用货币

c# - 客户端或服务器端的数据处理

c# - iges文件怎么写?

c++ - 将 "normal"std::string 转换为 utf-8

android - 如何为每种语言(Cordova 到 Android)起一个 APP 名称