.net 使用DateTimeFormatInfo时,在生成结果字符串时使用哪种区域性?

9jyewag0  于 2023-02-17  发布在  .NET
关注(0)|答案(1)|浏览(120)

当我使用DateTimeFormatInfo时,有时使用当前线程区域性来生成结果字符串,有时使用从它获得的区域性。也有使用不变区域性的情况。它背后的逻辑是什么?

bttbmeg0

bttbmeg01#

当我们构建DateTimeFormatInfo时,它总是指定格式字符串,如果我们将其作为IFormatProvider传递给ToStringstring.Format方法,它的日历也用于显示日期时间(由日历计算的日期元素)但是如果我们没有通过它,默认情况下,当前区域性信息作为IFormatProvider传递,因此当前区域性日历用于计算日期时间元素。在四种特殊情况下,不管您用于创建DateTimeFormatInfo或传递给这些方法的每个IFormatProvider的区域性如何,都使用了固定区域性和固定日历。"O" (or "o"), "R" (or "r"), "s", and "u"。下面的示例显示了一些示例:

static void ChangeStandardFormatStringAssociation()
    {
        // Build a writable instance of DateTimeFormatInfo which is get from writable CultureInfo (for example using ctor or using CreateSpecificCulture)
        var formatInfo = CultureInfo.CreateSpecificCulture("en-US").DateTimeFormat; // d standard format associated by "MM-dd-yyyy" in short Date for en-US but we want to change it to "dd-MM-yyyy"
        Console.WriteLine($"Culture which FormatInfo built from:en-US (This can not calculate from FormatInfo)");
        Console.WriteLine($"FormatInfo is readonly?{formatInfo.IsReadOnly}");
        Console.WriteLine(formatInfo.ShortDatePattern);
        CultureInfo.CurrentCulture = new CultureInfo("fa-IR");
        // What is current culture?
        Console.WriteLine($"Current Culture is :{Thread.CurrentThread.CurrentCulture.Name}");
        var dt = DateTime.Now.ToUniversalTime();
        Console.WriteLine($"{dt:d} (Current Culture)");// consider that if we do not specify formatInfo it uses the current culture 
        Console.WriteLine($"{dt.ToString("d", formatInfo)} (Culture which formatInfo built from)"); // It uses Calendar related to that cultureInfo and then calculate parts of given date in that culture and shows them
        Console.WriteLine($"{dt.ToString(formatInfo.ShortDatePattern)} (Culture which formatinfo build from Get the format string and calendar properties from current culture is used)");
        Console.WriteLine($"{dt.ToString("r", CultureInfo.CurrentCulture)} (Invariant Culture and Invariant Calendar used Even we pass other culture info)");
        Console.WriteLine($"{dt.ToString(formatInfo.ShortDatePattern, formatInfo)} (Culture which formatinfo build from Get the format string and calendar properties from that culture is also used since we set it as format provider)");

    }

相关问题