簡體   English   中英

如何將DateTime轉換為具有本地化的小數秒的字符串?

[英]How can I convert a DateTime to a string with fractional seconds that is localized?

我有一個DateTime對象,我想將小時,分鍾,秒和小數秒輸出為針對當前區域性而本地化的字符串。

這有兩個問題。

第一個問題是沒有標准的DateTime格式顯示小數秒。 我本質上想知道如何獲取長時間的 DateTime格式,但要用小數秒。

我當然可以獲取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);

我認為應該適用於每種文化,它沒有與時間分隔符相同的十進制分隔符,但這是一個假設。

注意:雖然可以同時解決這兩個問題,但對於我的特定應用程序,我比使用標准日期時間格式對用小數秒定位自定義日期時間格式更感興趣。

第一個問題是沒有標准的DateTime格式顯示小數秒。 我本質上想知道如何獲取長時間的DateTime格式,但要用小數秒。

您可能會考慮采用長格式,而只是將“: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);

更復雜的是,某些區域性具有日期時間格式,這些日期時間格式使用句點作為其格式的一部分。 這使得很難放置占位符(例如句點)並用區域性特定的小數點分隔符替換它。 除此之外,最終應該將價值放在正確的位置。 即使值是精確的秒(或半秒,等等),您是否肯定也總是要三位數? .FFF請使用.FFF

我懷疑這就是為什么不使用特定於文化的小數點分隔符的原因 我自己發現這很奇怪-的確,即使我不確信這是正確的 ,我也使Noda Time的行為方式相同。

最終,很多像這樣的問題是根本問題:如果一個文化沒有固定的代表“以分數秒的時間”的方式,你一定要代表小數秒,那么最好你要能夠做到有點糾結。

我認為這將為您提供接近所需的東西

var now = DateTime.Now;
var seconds = now.TimeOfDay.TotalSeconds % 60;
var timeText = string.Format(CultureInfo.GetCultureInfo("fr-FR"), 
                             "{0:d} {0:hh:mm:}{1:00.000}", now, seconds);

或只是使用

var timeText = string.Format(CultureInfo.CurrentCulture, 
                             "{0:d} {0:hh:mm:}{1:00.000}", now, seconds);

例如

  • fr-FR:20/03/2012 10:20:10,088
  • zh-CN:20/03/2012 10:21:08.724
  • zh-CN:2012/3/20 10:21:24.470

通常,我會更改當前的文化,並執行所需的操作。

System.Globalization.CultureInfo before = System.Threading.Thread.CurrentThread.CurrentCulture;
try
{
    System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

    string timestr = DateTime.Now.ToString();
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}
finally
{
    System.Threading.Thread.CurrentThread.CurrentUICulture = before;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM