全球化日期/时间/数字格式Globalize your date/time/number formats

通过适当设置日期、时间、数字、电话号码和货币的格式,设计全球通用的应用。Design your app to be global-ready by appropriately formatting dates, times, numbers, phone numbers, and currencies. 稍后即可调整应用,以适应全球市场中更多的文化、区域和语言。You'll then be able later to adapt your app for additional cultures, regions, and languages in the global market.

简介Introduction

创建应用时,如果考虑到多种语言和文化,则在应用向新市场发展时出现的意外问题将更少(如果有)。When creating your app, if you think more broadly than a single language and culture then you'll have fewer (if any) unexpected issues when your app grows into new markets. 例如,日期、时间、数字、日历、货币、电话号码、度量单位和纸张大小的显示都会因文化或语言的不同而有所不同。For example, dates, times, numbers, calendars, currency, telephone numbers, units of measurement, and paper sizes are all items that can be displayed differently in different cultures or languages.

不同地区和文化使用不同的日期和时间格式。Different regions and cultures use different date and time formats. 它们包含在以下方面的使用惯例:日期中的日和月顺序、时间中的小时和分钟的分隔,甚至用作分隔符的标点符号。These include conventions for the order of day and month in the date, for the separation of hours and minutes in the time, and even for what punctuation is used as a separator. 此外,可以采用各种长格式(“星期三,2012 年 3 月 28 日”)或短格式(“12/3/28”)显示日期,这些格式因文化而异。In addition, dates may be displayed in various long formats ("Wednesday, March 28, 2012") or short formats ("3/28/12"), which vary across cultures. 当然,星期中某天和年份中的某月的名称和缩写也因语言而异。And, of course, the names and abbreviations for the days of the week and months of the year differ between languages.

可以预览用于不同语言的格式。You can preview the formats used for different languages. 转到Settings > "设置" "时间" & 语言 > 区域 & 语言",然后单击"其他日期、时间、& 区域设置 > 更改日期、时间或数字格式"。Go to Settings > Time & Language > Region & language, and click Additional date, time, & regional settings > Change date, time, or number formats. 格式选项卡上,从格式下拉菜单中选择一种语言,并在示例中预览此格式。On the Formats tab, select a language from the Format drop-down and preview the formats in Examples.

本主题使用术语“用户配置文件语言列表”、“应用清单语言列表”和“应用运行时语言列表”。This topic uses the terms "user profile language list", "app manifest language list", and "app runtime language list". 有关这些术语到底款意味着什么,以及如何访问其值的详细信息,请参阅了解用户配置文件语言和应用清单语言For details on exactly what those terms mean and how to access their values, see Understand user profile languages and app manifest languages.

设置应用运行时语言列表的日期和时间格式Format dates and times for the app runtime language list

如果你需要允许用户选择日期或选择时间,请使用标准的日历、日期和时间控件If you need to allow users to choose a date, or to select a time, then use the standard calendar, date, and time controls. 它们将自动为应用运行时语言列表使用最佳日期和时间格式。These automatically use the best date and time format for the app runtime language list.

如果你需要自行显示日期或时间,则可以使用 DateTimeFormatter 类。If you need to display dates or times yourself then you can use the DateTimeFormatter class. 默认情况下,DateTimeFormatter 将自动为应用运行时语言列表使用最佳日期和时间格式。By default, DateTimeFormatter automatically uses the best date and time format for the app runtime language list. 因此,以下代码针对该列表以最佳方式设置给定日期时间的格式。So, the code below formats a given DateTime in the best way for that list. 例如,假设你的应用清单语言列表包括英语(美国)(默认语言)和德语(德国)。As an example, assume that your app manifest language list includes English (United States), which is also your default, and German (Germany). 如果当前日期为 2017 年 11 月 6 日,并且用户配置文件语言列表首先包含德语(德国),则格式化程序将呈现“06.11.2017”。If the current date is Nov 6 2017 and the user profile language list contains German (Germany) first, then the formatter gives "06.11.2017". 如果用户配置文件语言列表首先包含英语(美国)(或既不包含英语,也不包含德语),则格式化程序将呈现“11/6/2017”(因为“en-US”匹配,或用作默认语言)。If the user profile language list contains English (United States) first (or if it contains neither English nor German), then the formatter gives "11/6/2017" (since "en-US" matches, or is used as the default).

    // Use the DateTimeFormatter class to display dates and times using basic formatters.

    var shortDateFormatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("shortdate");
    var shortTimeFormatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("shorttime");

    var dateTimeToFormat = DateTime.Now;

    var shortDate = shortDateFormatter.Format(dateTimeToFormat);
    var shortTime = shortTimeFormatter.Format(dateTimeToFormat);

    var results = "Short Date: " + shortDate + "\n" +
                  "Short Time: " + shortTime;

可在你自己的电脑上按此操作测试以上代码。You can test the code above on your own PC like this.

设置用户配置文件语言列表的日期和时间格式Format dates and times for the user profile language list

请记住,默认情况下,DateTimeFormatter 匹配应用运行时语言列表。Remember that, by default, DateTimeFormatter matches the app runtime language list. 这样,如果显示“日期为 <date>”等字符串,语言将匹配日期格式。That way, if you display strings such as "The date is <date>", then the language will match the date format.

如果无论出于何种原因想要仅根据用户配置文件语言列表设置日期和/或时间的格式,则可以使用类似于以下示例的代码执行此操作。If for whatever reason you want to format dates and/or times only according to the user profile language list, then you can do that using code like the example below. 但如果执行了此操作,则将了解到,用户可以选择你的应用没有将字符串翻译为某种语言的语言。But if you do so then understand that the user can choose a language for which your app doesn't have translated strings. 例如,如果你的应用未本地化为德语(德国),但用户将该语言作为其首选语言,则可能导致显示有争议的奇怪字符串,例如“日期为 06.11.2017”。For example, if your app is not localized into German (Germany), but the user chooses that as their preferred language, then that could result in the display of arguably odd-looking strings such as "The date is 06.11.2017".

    // Use the DateTimeFormatter class to display dates and times using basic formatters.

    var userLanguages = Windows.System.UserProfile.GlobalizationPreferences.Languages;

    var shortDateFormatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("shortdate", userLanguages);

    var results = "Short Date: " + shortDateFormatter.Format(DateTime.Now);

设置适当的数字和货币格式Format numbers and currencies appropriately

不同的文化设置数字格式的方式也不相同。Different cultures format numbers differently. 格式差异可能包括显示多少小数位数、什么字符用作小数分隔符以及要使用什么货币符号。Format differences may include how many decimal digits to display, what characters to use as decimal separators, and what currency symbol to use. 使用 NumberFormatting 命名空间中的类来显示小数、分数、千分比和货币。Use classes in the NumberFormatting namespace to display decimal, percent, or permille numbers, and currencies. 大多数情况下,建议使用这些格式化程序类,将最佳格式用于用户配置文件。Most of the time, you will want these formatter classes to use the best format for the user profile. 但是你可以使用格式化程序显示任何区域或格式的货币。But you may use the formatters to display a currency for any region or format.

此示例展示如何按照用户配置文件和针对特定给定货币系统来显示货币。This example shows how to display currencies both per the user profile, and for a specific given currency system.

    // This scenario uses the CurrencyFormatter class to format a number as a currency.

    var userCurrency = Windows.System.UserProfile.GlobalizationPreferences.Currencies[0];

    var valueToBeFormatted = 12345.67;

    var userCurrencyFormatter = new Windows.Globalization.NumberFormatting.CurrencyFormatter(userCurrency);
    var userCurrencyValue = userCurrencyFormatter.Format(valueToBeFormatted);

    // Create a formatter initialized to a specific currency,
    // in this case US Dollar (specified as an ISO 4217 code) 
    // but with the default number formatting for the current user.
    var currencyFormatUSD = new Windows.Globalization.NumberFormatting.CurrencyFormatter("USD");
    var currencyValueUSD = currencyFormatUSD.Format(valueToBeFormatted);

    // Create a formatter initialized to a specific currency.
    // In this case it's the Euro with the default number formatting for France.
    var currencyFormatEuroFR = new Windows.Globalization.NumberFormatting.CurrencyFormatter("EUR", new[] { "fr-FR" }, "FR");
    var currencyValueEuroFR = currencyFormatEuroFR.Format(valueToBeFormatted);

    // Results for display.
    var results = "Fixed number (" + valueToBeFormatted + ")\n" +
                    "With user's default currency: " + userCurrencyValue + "\n" +
                    "Formatted US Dollar: " + currencyValueUSD + "\n" +
                    "Formatted Euro (fr-FR defaults): " + currencyValueEuroFR;

可以通过在 "设置时间" 中更改国家或地区来测试上面的代码Settings > & 语言 > 区域 & 语言" > 国家或地区"。You can test the code above on your own PC by changing the country or region in Settings > Time & Language > Region & language > Country or region. 选择一个国家或地区(如冰岛),并再次运行代码。Choose a country or region (perhaps Iceland), and run the code again.

使用与文化相对应的日历Use a culturally appropriate calendar

日历因区域和语言而异。The calendar differs across regions and languages. 并非每一个区域都使用公历作为默认日历。The Gregorian calendar is not the default for every region. 某些区域的用户可能选择其他日历,例如日本历或伊斯兰历。Users in some regions may choose alternate calendars, such as the Japanese era calendar, or Arabic lunar calendars. 日历上的日期和时间还对不同的时区和夏令时敏感。Dates and times on the calendar are also sensitive to different time zones and daylight-saving time.

为确保使用首选的日历格式,可使用标准的日历、日期和时间控件To ensure that the preferred calendar format is used, you can use the standard calendar, date, and time controls. 对于可能需要对日历日期直接操作的更加复杂的方案,Windows.Globalization 提供了一个 Calendar 类,该类为给定的文化、区域和日历类型提供适当的日历表示。For more complex scenarios, where working directly with operations on calendar dates may be required, Windows.Globalization provides a Calendar class that gives an appropriate calendar representation for the given culture, region, and calendar type.

设置相应的电话号码Format phone numbers appropriately

设置电话号码格式的方式因区域而异。Phone numbers are formatted differently across regions. 电话号码的数字位数、数字组合方式和某些部分的重要性因国家/地区而异。The number of digits, how the digits are grouped, and the significance of certain parts of the phone number vary between countries. 从 Windows 10 版本 1607 开始,可以使用 PhoneNumberFormatting 命名空间中的类为当前区域设置适当的电话号码格式。Starting in Windows 10, version 1607, you can use classes in the PhoneNumberFormatting namespace to format phone numbers appropriately for the current region.

PhoneNumberInfo 可解析一串数字,并允许你:确定这些数字在当前区域中是否是有效的电话号码;比较两组数字是否相等;提取电话号码的不同功能部分,例如国家/地区代码或地理区域代码。PhoneNumberInfo parses a string of digits and allows you to: determine whether the digits are a valid phone number in the current region; compare two numbers for equality; and to extract the different functional parts of the phone number, such as country code or geographical area code.

PhoneNumberFormatter将数字字符串或PhoneNumberInfo的格式设置为显示,即使数字字符串表示部分电话号码也是如此。PhoneNumberFormatter formats a string of digits or a PhoneNumberInfo for display, even when the string of digits represents a partial phone number. 你可以使用此部分号码格式设置,将号码设置为用户输入该号码时所示的格式。You can use this partial number formatting to format a number as a user is entering the number.

下面的示例显示了如何使用 PhoneNumberFormatter 将电话号码设置为输入时所示的格式。The example below shows how to use PhoneNumberFormatter to format a phone number as it is being entered. 每当名为 phoneNumberInputTextBox 的 TextBox 中的文本发生更改时,文本框内容都会使用当前默认区域进行格式设置并显示在名为 phoneNumberOutputTextBlock 的 TextBlock 中。Each time text changes in a TextBox named phoneNumberInputTextBox, the contents of the text box are formatted using the current default region and displayed in a TextBlock named phoneNumberOutputTextBlock. 出于演示目的,该字符串也使用新西兰区域进行格式设置,并显示在名为 phoneNumberOutputTextBlockNZ 的 TextBlock 中。For demonstration purposes, the string is also formatted using the region for New Zealand, and displayed in a TextBlock named phoneNumberOutputTextBlockNZ.

    using Windows.Globalization.PhoneNumberFormatting;

    PhoneNumberFormatter currentFormatter, NZFormatter;

    public MainPage()
    {
        this.InitializeComponent();

        // Use the default formatter for the current region
        this.currentFormatter = new PhoneNumberFormatter();

        // Create an explicit formatter for New Zealand. 
        PhoneNumberFormatter.TryCreate("NZ", out this.NZFormatter);
    }

    private void phoneNumberInputTextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        // Format for the default region.
        this.phoneNumberOutputTextBlock.Text = currentFormatter.FormatPartialString(this.phoneNumberInputTextBox.Text);

        // If the NZFormatter was created successfully, format the partial string for the NZ TextBlock.
        if(this.NZFormatter != null)
        {
            this.phoneNumberOutputTextBlockNZ.Text = this.NZFormatter.FormatPartialString(this.phoneNumberInputTextBox.Text);
        }
    }

可以通过在 "设置时间" 中更改国家或地区来测试上面的代码Settings > & 语言 > 区域 & 语言" > 国家或地区"。You can test the code above on your own PC by changing the country or region in Settings > Time & Language > Region & language > Country or region. 选择一个国家或地区(可能是新西兰,以便确认格式匹配),并再次运行代码。Choose a country or region (perhaps New Zealand to confirm that the formats match), and run the code again. 对于测试数据,可以针对新西兰的商业电话号码进行 Web 搜索。For test data, you can do a web search for the phone number of a business in New Zealand.

用户的语言和文化首选项The user's language and cultural preferences

对于想要仅基于用户的语言、区域或文化首选项提供不同功能的方案,Windows 为你提供了一种访问这些首选项的方法:通过 Windows.System.UserProfile.GlobalizationPreferencesFor scenarios where you wish to provide different functionality based solely on the user's language, region, or cultural preferences, Windows gives you a way to access those preferences, through Windows.System.UserProfile.GlobalizationPreferences. 需要时,使用 GlobalizationPreferences 类获取用户当前地理区域、首选语言、首选货币等项目的值。When needed, use the GlobalizationPreferences class to get the value of the user's current geographic region, preferred languages, preferred currencies, and so on. 但请记住,如果应用的字符串/图像未针对用户的首选语言进行本地化,则针对该首选语言进行格式设置的日期、时间和其他数据将与你显示的字符串不匹配。But remember that if your app's strings/images aren't localized for the user's preferred language then dates and times and other data formatted for that preferred language won't match the strings that you display.

重要的 APIImportant APIs

示例Samples