openharmony 鸿蒙 js-apis-i18n

2025-06-12 浏览 (1)

@ohos.i18n (Internationalization)

This module provides system-related or enhanced i18n capabilities, such as locale management, phone number formatting, and calendar, through supplementary I18N APIs that are not defined in ECMA 402. The intl module provides basic i18n capabilities through the standard i18n APIs defined in ECMA 402. It works with the i18n module to provide a complete suite of i18n capabilities.

NOTE

  • The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.

  • The APIs of this module conform to the Common Locale Data Repository (CLDR) internationalization database. The processing result may change with CLDR evolution. API version 12 corresponds to CLDR 42. For details about data changes, visit the official website.

  • Since API version 11, some APIs of this module are supported in ArkTS widgets.

Modules to Import

import { i18n } from '@kit.LocalizationKit';

System9+

getDisplayCountry9+

static getDisplayCountry(country: string, locale: string, sentenceCase?: boolean): string

Obtains the country/region display name in the specified language.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
countrystringYesValie country/region code.
localestringYesSystem locale, which consists of the language, script, and country/region.
sentenceCasebooleanNoWhether to use sentence case to display the text. The value true means to display the text in title case format, and the value false means to display the text in the default case format of the locale. The default value is true.

Return value

TypeDescription
stringCountry/region display name in the specified language.

Error codes

For details about the error codes, see ohos.i18n Error Codes and Universal Error Codes.

IDError Message
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.
890001Invalid parameter. Possible causes: Parameter verification failed.

Description

The error message of 890001 is subject to the actual error.

Example

import { BusinessError } from '@kit.BasicServicesKit';

try {
  let displayCountry: string = i18n.System.getDisplayCountry('CN', 'en-GB'); // displayCountry = 'China'
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`);
}

getDisplayLanguage9+

static getDisplayLanguage(language: string, locale: string, sentenceCase?: boolean): string

Obtains the language display name in the specified language.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
languagestringYesValid language ID.
localestringYesSystem locale, which consists of the language, script, and country/region.
sentenceCasebooleanNoWhether to use sentence case to display the text. The value true means to display the text in title case format, and the value false means to display the text in the default case format of the locale. The default value is true.

Return value

TypeDescription
stringLanguage display name in the specified language.

Error codes

For details about the error codes, see ohos.i18n Error Codes and Universal Error Codes.

IDError Message
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.
890001Invalid parameter. Possible causes: Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';

try {
  // Obtain the display name of Chinese in English.
  let displayLanguage: string = i18n.System.getDisplayLanguage('zh', 'en-GB'); // displayLanguage = 'Chinese'
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`call System.getDisplayLanguage failed, error code: ${err.code}, message: ${err.message}.`);
}

getSystemLanguages9+

static getSystemLanguages(): Array<string>

Obtains the list of system languages.

Since API version 11, this API is supported in ArkTS widgets.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Return value

TypeDescription
Array<string>List of system languages.

Example

// systemLanguages = [ 'ug', 'bo', 'zh-Hant', 'en-Latn-US', 'zh-Hans' ]
let systemLanguages: Array<string> = i18n.System.getSystemLanguages();

getSystemCountries9+

static getSystemCountries(language: string): Array<string>

Obtains the list of countries/regions supported for the specified language.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
languagestringYesValid language ID.

Return value

TypeDescription
Array<string>List of countries/regions supported for the specified language.

Error codes

For details about the error codes, see ohos.i18n Error Codes and Universal Error Codes.

IDError Message
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.
890001Invalid parameter. Possible causes: Parameter verification failed.

Description

The error message of 890001 is subject to the actual error.

Example

import { BusinessError } from '@kit.BasicServicesKit';

try {
  // systemCountries = [ 'ZW', 'YT', 'YE', ..., 'ER', 'CN', 'DE' ]
  let systemCountries: Array<string> = i18n.System.getSystemCountries('zh');
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`call System.getSystemCountries failed, error code: ${err.code}, message: ${err.message}.`);
}

isSuggested9+

static isSuggested(language: string, region?: string): boolean

Checks whether a language is a suggested language in the specified region. It can be used for region-based language recommendation or language-based region recommendation.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
languagestringYesValid language ID, for example, zh.
regionstringNoValid region ID, for example, CN.
The default value is the country/region of the SIM card.

Return value

TypeDescription
booleanWhether a language is a suggested language. The value true indicates that the language is a suggested language of the region, the the value false indicates the opposite.

Error codes

For details about the error codes, see ohos.i18n Error Codes and Universal Error Codes.

IDError Message
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.
890001Invalid parameter. Possible causes: Parameter verification failed.

Description

The error message of 890001 is subject to the actual error.

Example

import { BusinessError } from '@kit.BasicServicesKit';

try {
  let isSuggestedCountry: boolean = i18n.System.isSuggested('zh', 'CN'); // isSuggestedCountry = true
  isSuggestedCountry = i18n.System.isSuggested('en'); // Check whether a language is a suggested language for the current system region.
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`call System.isSuggested failed, error code: ${err.code}, message: ${err.message}.`);
}

getSystemLanguage9+

static getSystemLanguage(): string

Obtains the current system language.

Atomic service API: This API can be used in atomic services since API version 11.

Widget capability: Since API version 11, this feature is supported in ArkTS widgets.

System capability: SystemCapability.Global.I18n

Return value

TypeDescription
stringLanguage ID.

Example

let systemLanguage: string = i18n.System.getSystemLanguage();

getSystemRegion9+

static getSystemRegion(): string

Obtains the current system country/region.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Return value

TypeDescription
stringCountry/region ID.

Example

let systemRegion: string = i18n.System.getSystemRegion();

getSystemLocale9+

static getSystemLocale(): string

Obtains the current system locale.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Global.I18n

Return value

TypeDescription
stringLocale ID.

Example

let systemLocale: string = i18n.System.getSystemLocale();

is24HourClock9+

static is24HourClock(): boolean

Checks whether the 24-hour clock is used.

Widget capability: Since API version 11, this feature is supported in ArkTS widgets.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Return value

TypeDescription
booleanWhether the 24-hour clock is used. The value true indicates that the 24-hour clock is used, the the value false means the opposite.

Example

let is24HourClock: boolean = i18n.System.is24HourClock();

getPreferredLanguageList9+

static getPreferredLanguageList(): Array<string>

Obtains the list of preferred languages.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Return value

TypeDescription
Array<string>List of preferred languages.

Example

let preferredLanguageList: Array<string> = i18n.System.getPreferredLanguageList();

getFirstPreferredLanguage9+

static getFirstPreferredLanguage(): string

Obtains the first language in the preferred language list.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Return value

TypeDescription
stringFirst language in the preferred language list.

Example

let firstPreferredLanguage: string = i18n.System.getFirstPreferredLanguage();

setAppPreferredLanguage11+

static setAppPreferredLanguage(language: string): void

Sets the preferred language of the application. Resources are loaded in the preferred language when the application is launched. If the preferred language is set to default, the application's language will be the same as the system language, and the setting will take effect upon cold starting of the application.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
languagestringYesValid language ID or default.

Error codes

For details about the error codes, see ohos.i18n Error Codes and Universal Error Codes.

IDError Message
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.
890001Invalid parameter. Possible causes: Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';

try {
  i18n.System.setAppPreferredLanguage('zh');
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`call System.setAppPreferredLanguage failed, error code: ${err.code}, message: ${err.message}.`);
}

getAppPreferredLanguage9+

static getAppPreferredLanguage(): string

Obtains the preferred language of an application.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Return value

TypeDescription
stringPreferred language of the application.

Example

let appPreferredLanguage: string = i18n.System.getAppPreferredLanguage();

getUsingLocalDigit9+

static getUsingLocalDigit(): boolean

Checks whether use of local digits is enabled.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Return value

TypeDescription
booleanWhether use of local digits is enabled. The value true indicates that use of local digits is enabled, and the value false indicates the opposite.

Example

let usingLocalDigit: boolean = i18n.System.getUsingLocalDigit();

getSimplifiedLanguage15+

static getSimplifiedLanguage(language?: string): string

Obtains the simplified representation of a language. For example, the simplified representation of en-Latn-US is en, and that of en-Latn-GB is en-GB.

Atomic service API: This API can be used in atomic services since API version 15.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
languagestringNoValid language ID. The default value is the system language.

Return value

TypeDescription
stringIf language is not passed, the application checks for dialects supported by the system based on the system language and locale. If such a dialect is found, the simplified representation of the dialect is returned. Otherwise, the simplified representation of the system language is returned.
If language is passed, the simplified representation of the specified language is returned.

Error codes

For details about the error codes, see ohos.i18n Error Codes and Universal Error Codes.

IDError Message
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.
890001Invalid parameter. Possible causes: Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';

try {
  // simplifiedLanguage = 'zh'
  let simplifiedLanguage: string = i18n.System.getSimplifiedLanguage('zh-Hans-CN');
  // Obtain the simplified representation of the current system language.
  let simplifiedSystemLanguage: string = i18n.System.getSimplifiedLanguage();
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`call System.getSimplifiedLanguage failed, error code: ${err.code}, message: ${err.message}.`);
}

getTemperatureType18+

static getTemperatureType(): TemperatureType

Obtains the temperature unit of the system.

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.Global.I18n

Return value

TypeDescription
TemperatureTypeTemperature unit.

Example

let temperatureType: i18n.TemperatureType = i18n.System.getTemperatureType();

getTemperatureName18+

static getTemperatureName(type: TemperatureType): string

Obtains the name of a temperature unit.

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
typeTemperatureTypeYesTemperature unit.

Return value

TypeDescription
stringName of the temperature unit, which can be celsius, fahrenheit, and kelvin.

Error codes

For details about the error codes, see i18n Error Codes.

IDError Message
890001Invalid parameter. Possible causes: Parameter verification failed.

Description

The error message of 890001 is subject to the actual error.

Example

import { BusinessError } from '@kit.BasicServicesKit';

try {
  // temperatureName = 'celsius'
  let temperatureName: string = i18n.System.getTemperatureName(i18n.TemperatureType.CELSIUS);
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`call System.getTemperatureName failed, error code: ${err.code}, message: ${err.message}.`);
}

getFirstDayOfWeek18+

static getFirstDayOfWeek(): WeekDay

Obtains the first day of a week in the system settings.

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.Global.I18n

Return value

TypeDescription
WeekDayStart day of a week.

Example

let firstDayOfWeek: i18n.WeekDay = i18n.System.getFirstDayOfWeek();

TemperatureType18+

Enumerates temperature units.

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.Global.I18n

NameValueDescription
CELSIUS1Celsius.
FAHRENHEIT2Fahrenheit.
KELVIN3Kelvin.

WeekDay18+

Enumerates the first day of a week. The value ranges from Monday to Sunday.

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.Global.I18n

NameValueDescription
MON1Monday.
TUE2Tuesday.
WED3Wednesday.
THU4Thursday.
FRI5Friday.
SAT6Saturday.
SUN7Sunday.

i18n.isRTL

isRTL(locale: string): boolean

Checks whether a language is an RTL language. For an RTL language, UI mirroring is required.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
localestringYesSystem locale, which consists of the language, script, and country/region.

Return value

TypeDescription
booleanWhether a language is an RTL language. The value true indicates that the language is an RTL language, and the value false indicates the opposite.

Example

let isZhRTL: boolean = i18n.isRTL('zh-CN'); // Since Chinese is not written from right to left, false is returned.
let isArRTL: boolean = i18n.isRTL('ar-EG'); // Since Arabic is written from right to left, true is returned.

i18n.getCalendar8+

getCalendar(locale: string, type? : string): Calendar

Obtains the Calendar object for the specified locale and calendar type.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
localestringYesLocale ID, which consists of the language, script, and country/region, for example, zh-Hans-CN.
typestringNoCalendar. The value can be buddhist, chinese, coptic, ethiopic, hebrew, gregory, indian, islamic_civil, islamic_tbla, islamic_umalqura, japanese,  or persian.
The default value is the default calendar of the locale. For details about the meanings and application scenarios of different values, see Calendar Setting .

Return value

TypeDescription
CalendarCalendar object.

Example

let calendar: i18n.Calendar = i18n.getCalendar('zh-Hans', 'chinese'); // Obtain the Calendar object for the Chinese lunar calendar.

EntityRecognizer11+

constructor11+

constructor(locale?: string)

Creates an entityRecognizer object. This object is used to recognize entities in the text for the specified locale.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
localestringNoLocale ID, which consists of the language, script, and country/region, for example, zh-Hans-CN.
The default value is the current system locale.

Error codes

For details about the error codes, see ohos.i18n Error Codes and Universal Error Codes.

IDError Message
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.
890001Invalid parameter. Possible causes: Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';

try {
  let entityRecognizer: i18n.EntityRecognizer = new i18n.EntityRecognizer('zh-CN');
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`call new i18n.EntityRecognizer failed, error code: ${err.code}, message: ${err.message}.`);
}

findEntityInfo11+

findEntityInfo(text: string): Array<EntityInfoItem>

Obtains entity information in the text object.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
textstringYestext object.

Return value

TypeDescription
Array<EntityInfoItem>List of entities in the text.

Error codes

For details about the error codes, see Universal Error Codes.

IDError Message
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.

Example

import { BusinessError } from '@kit.BasicServicesKit';

try {
  let entityRecognizer: i18n.EntityRecognizer = new i18n.EntityRecognizer('zh-CN');
  let phoneNumberText: string = 'If you have any questions, call us by phone 12345678.';
  // phoneNumberEntity[0].type = 'phone_number', phoneNumberEntity[0].begin = 8, phoneNumberEntity[0].end = 19
  let phoneNumberEntity: Array<i18n.EntityInfoItem> = entityRecognizer.findEntityInfo(phoneNumberText);
  let dateText: string = 'Let's have dinner on December 1, 2023.';
  // dateEntity[0].type = 'date', dateEntity[0].begin = 2, dateEntity[0].end = 12
  let dateEntity: Array<i18n.EntityInfoItem> = entityRecognizer.findEntityInfo(dateText);
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`call EntityRecognizer.findEntityInfo failed, error code: ${err.code}, message: ${err.message}.`);
}

EntityInfoItem11+

Defines a list of entities.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

NameTypeReadableWritableDescription
typestringYesYesEntity type. The value can be phone_number or date. phone_number indicates that the entity is a phone number, and date indicates that the entity is a date.
beginnumberYesYesStart position of the entity in the input string.
endnumberYesYesEnd position of the entity the input string.

Calendar8+

setTime8+

setTime(date: Date): void

Sets the date and time for a Calendar object.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
dateDateYesDate and time. Note: The month starts from 0. For example, 0 indicates January.

Example

let calendar: i18n.Calendar = i18n.getCalendar('en-US', 'gregory');
let date: Date = new Date(2021, 10, 7, 8, 0, 0); // The date and time is 2021.11.07 08:00:00.
calendar.setTime(date);

setTime8+

setTime(time: number): void

Sets the date and time for a Calendar object.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
timenumberYesUnix timestamp, which indicates the number of milliseconds that have elapsed since the Unix epoch.

Example

let calendar: i18n.Calendar = i18n.getCalendar('en-US', 'gregory');
calendar.setTime(10540800000);

set8+

set(year: number, month: number, date:number, hour?: number, minute?: number, second?: number): void

Sets the year, month, day, hour, minute, and second for this Calendar object.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
yearnumberYesYear to set.
monthnumberYesMonth to set. Note: The month starts from 0. For example, 0 indicates January.
datenumberYesDay to set.
hournumberNoHour to set. The default value is the current system time.
minutenumberNoMinute to set. The default value is the current system time.
secondnumberNoSecond to set. The default value is the current system time.

Example

let calendar: i18n.Calendar = i18n.getCalendar('zh-Hans');
calendar.set(2021, 10, 1, 8, 0, 0); // Set the date and time to 2021.11.1 08:00:00.

setTimeZone8+

setTimeZone(timezone: string): void

Sets the time zone of this Calendar object.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
timezonestringYesValid time zone ID, for example, Asia/Shanghai.

Example

let calendar: i18n.Calendar = i18n.getCalendar('zh-Hans');
calendar.setTimeZone('Asia/Shanghai');

getTimeZone8+

getTimeZone(): string

Obtains the time zone ID of this Calendar object.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Return value

TypeDescription
stringTime zone ID.

Example

let calendar: i18n.Calendar = i18n.getCalendar('zh-Hans');
calendar.setTimeZone('Asia/Shanghai');
let timezone: string = calendar.getTimeZone(); // timezone = 'Asia/Shanghai'

getFirstDayOfWeek8+

getFirstDayOfWeek(): number

Obtains the first day of a week for this Calendar object.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Return value

TypeDescription
numberFirst day of a week. The value 1 indicates Sunday, and the value 7 indicates Saturday.

Example

let calendar: i18n.Calendar = i18n.getCalendar('en-US', 'gregory');
let firstDayOfWeek: number = calendar.getFirstDayOfWeek(); // firstDayOfWeek = 1

setFirstDayOfWeek8+

setFirstDayOfWeek(value: number): void

Sets the first day of a week for this Calendar object.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
valuenumberYesStart day of a week. The value 1 indicates Sunday, and the value 7 indicates Saturday.

Example

let calendar: i18n.Calendar = i18n.getCalendar('zh-Hans');
calendar.setFirstDayOfWeek(3);
let firstDayOfWeek: number = calendar.getFirstDayOfWeek(); // firstDayOfWeek = 3

getMinimalDaysInFirstWeek8+

getMinimalDaysInFirstWeek(): number

Obtains the minimum number of days in the first week for this Calendar object.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Return value

TypeDescription
numberMinimum number of days in the first week of a year.

Example

let calendar: i18n.Calendar = i18n.getCalendar('zh-Hans');
let minimalDaysInFirstWeek: number = calendar.getMinimalDaysInFirstWeek(); // minimalDaysInFirstWeek = 1

setMinimalDaysInFirstWeek8+

setMinimalDaysInFirstWeek(value: number): void

Sets the minimum number of days in the first week for this Calendar object.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
valuenumberYesMinimum number of days in the first week of a year.

Example

let calendar: i18n.Calendar = i18n.getCalendar('zh-Hans');
calendar.setMinimalDaysInFirstWeek(3);
let minimalDaysInFirstWeek: number = calendar.getMinimalDaysInFirstWeek(); // minimalDaysInFirstWeek = 3

get8+

get(field: string): number

Obtains the values of the calendar attributes in this Calendar object.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
fieldstringYesCalendar attributes. The following table lists the supported attribute values.
NameDescription
eraEra, for example, AD or BC.
yearYear.
monthMonth. Note: The month starts from 0. For example, 0 indicates January.
dateDate.
hourWall-clock hour.
hour_of_dayHour of day.
minuteMinute.
secondSecond.
millisecondMillisecond.
week_of_yearWeek of year. Note that the algorithm for calculating the first week of a year varies according to regions. For example, the first seven days in a year are the first week.
year_woyYear used with the week of year field.
week_of_monthWeek of month.
day_of_week_in_monthDay of week in month.
day_of_yearDay of year.
day_of_weekDay of week.
milliseconds_in_dayMilliseconds in day.
zone_offsetFixed time zone offset in milliseconds (excluding DST).
dst_offsetDST offset in milliseconds.
dow_localLocalized day of week.
extended_yearExtended year, which can be a negative number.
julian_dayJulian day.
is_leap_monthWhether a month is a leap month.

Return value

TypeDescription
numberValue of the calendar attribute. For example, if the year of the internal date of the current Calendar object is 1990, get('year') returns 1990.

Example

let calendar: i18n.Calendar = i18n.getCalendar('zh-Hans');
calendar.set(2021, 10, 1, 8, 0, 0); // Set the date and time to 2021.11.1 08:00:00.
let hourOfDay: number = calendar.get('hour_of_day'); // hourOfDay = 8

getDisplayName8+

getDisplayName(locale: string): string

Obtains calendar display name in the specified language.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
localestringYesSystem locale, which consists of the language, script, and country/region.

Return value

TypeDescription
stringCalendar display name in the specified language. For example, buddhist is displayed as Buddhist Calendar if the locale is en-US.

Example

let calendar: i18n.Calendar = i18n.getCalendar('en-US', 'buddhist');
let calendarName: string = calendar.getDisplayName('zh'); // calendarName = 'Buddhist'

isWeekend8+

isWeekend(date?: Date): boolean

Checks whether a given date is a weekend in this Calendar object.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
dateDateNoDate and time. Note: The month starts from 0. For example, 0 indicates January.
The default value is current date of the Calendar object.

Return value

TypeDescription
booleanThe value true indicates that the specified date is a weekend, and the value false indicates the opposite.

Example

let calendar: i18n.Calendar = i18n.getCalendar('zh-Hans');
calendar.set(2021, 11, 11, 8, 0, 0); // Set the time to 2021.12.11 08:00:00.
let isWeekend: boolean = calendar.isWeekend(); // isWeekend = true
let date: Date = new Date(2011, 11, 6, 9, 0, 0); // The date and time is 2011-12-06 09:00:00.
isWeekend = calendar.isWeekend(date); // isWeekend = false

add11+

add(field: string, amount: number): void

Performs addition or subtraction on the calendar attributes of this Calendar object.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
fieldstringYesCalendar attribute. The value can be any of the following: year, month, week_of_year, week_of_month, date, day_of_year, day_of_week, day_of_week_in_month, hour, hour_of_day, minute, second, millisecond.
For details about the values, see get.
amountnumberYesAddition or subtraction amount.

Error codes

For details about the error codes, see ohos.i18n Error Codes and Universal Error Codes.

IDError Message
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.
890001Invalid parameter. Possible causes: Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';

try {
  let calendar: i18n.Calendar = i18n.getCalendar('zh-Hans');
  calendar.set(2021, 11, 11, 8, 0, 0); // Set the date and time to 2021.12.11 08:00:00.
  calendar.add('year', 8); // 2021 + 8
  let year: number = calendar.get('year'); // year = 2029
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`call Calendar.add failed, error code: ${err.code}, message: ${err.message}.`);
}

getTimeInMillis11+

getTimeInMillis(): number

Obtains the timestamp of this Calendar object.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Return value

TypeDescription
numberUnix timestamp, which indicates the number of milliseconds that have elapsed since the Unix epoch.

Example

let calendar: i18n.Calendar = i18n.getCalendar('zh-Hans');
calendar.setTime(5000);
let millisecond: number = calendar.getTimeInMillis(); // millisecond = 5000

compareDays11+

compareDays(date: Date): number

Compares the current date of this Calendar object with the specified date for the difference in the number of days.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
dateDateYesDate and time. Note: The month starts from 0. For example, 0 indicates January.

Return value

TypeDescription
numberDifference in the number of days. A positive number indicates that the calendar date is earlier, and a negative number indicates the opposite.
The value is accurate to milliseconds. If the value is less than one day, it is considered as one day.

Error codes

For details about the error codes, see Universal Error Codes.

IDError Message
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.

Example

import { BusinessError } from '@kit.BasicServicesKit';

try {
  let calendar: i18n.Calendar = i18n.getCalendar('zh-Hans');
  calendar.setTime(5000);
  let date: Date = new Date(6000);
  let diff: number = calendar.compareDays(date); // diff = 1
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`call Calendar.compareDays failed, error code: ${err.code}, message: ${err.message}.`);
}

PhoneNumberFormat8+

constructor8+

constructor(country: string, options?: PhoneNumberFormatOptions)

Creates a PhoneNumberFormat object.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
countrystringYesCountry/region to which the phone number to be formatted belongs.
optionsPhoneNumberFormatOptionsNoOptions for PhoneNumberFormat object initialization. The default value is NATIONAL.

Example

let option: i18n.PhoneNumberFormatOptions = { type: 'E164' };
let phoneNumberFormat: i18n.PhoneNumberFormat = new i18n.PhoneNumberFormat('CN', option);

isValidNumber8+

isValidNumber(number: string): boolean

Checks whether the phone number is valid for the country/region in the PhoneNumberFormat object.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
numberstringYesPhone number to be checked.

Return value

TypeDescription
booleanWhether the phone number is valid. The value true indicates that the phone number is valid, and the value false indicates the opposite.

Example

let phonenumberfmt: i18n.PhoneNumberFormat = new i18n.PhoneNumberFormat('CN');
let isValidNumber: boolean = phonenumberfmt.isValidNumber('158****2312'); // isValidNumber = true

format8+

format(number: string): string

Formats a phone number.

Description Formatting dialed phone numbers is supported since API version 12.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
numberstringYesPhone number to be formatted.

Return value

TypeDescription
stringFormatted phone number.

Example

let phonenumberfmt: i18n.PhoneNumberFormat = new i18n.PhoneNumberFormat('CN');
// formattedPhoneNumber = '158 **** 2312'
let formattedPhoneNumber: string = phonenumberfmt.format('158****2312');

// Format the phone number being dialed.
let option: i18n.PhoneNumberFormatOptions = { type: 'TYPING' };
let phoneNumberFmt: i18n.PhoneNumberFormat = new i18n.PhoneNumberFormat('CN', option);
let phoneNumber: string = '130493';
let formatResult: string = '';
for (let i = 0; i < phoneNumber.length; i++) {
  formatResult += phoneNumber.charAt(i);
  formatResult = phoneNumberFmt.format(formatResult); // formatResult = '130 493'
}

getLocationName9+

getLocationName(number: string, locale: string): string

Obtains the home location of a phone number.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
numberstringYesPhone number. To obtain the home location of a number in other countries/regions, you need to prefix the number with 00 and the country code.
localestringYesSystem locale, which consists of the language, script, and country/region.

Return value

TypeDescription
stringHome location of the phone number. If the number is invalid, an empty string is returned.

Example

let phonenumberfmt: i18n.PhoneNumberFormat = new i18n.PhoneNumberFormat('CN');
let locationName: string = phonenumberfmt.getLocationName('158****2345', 'zh-CN'); // locationName = 'Zhanjiang, Guangdong Province'
let locName: string = phonenumberfmt.getLocationName('0039312****789', 'zh-CN'); // locName = 'Italy'

PhoneNumberFormatOptions8+

Options for PhoneNumberFormat object initialization.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

NameTypeReadableWritableDescription
typestringYesYesType of the phone number. The value can be E164, INTERNATIONAL, NATIONAL, RFC3966, or TYPING.
- In API version 8, type is mandatory.
- In API version 9 or later, type is optional.
- In API version 12 or later, TYPING is supported, which indicates that the dialed number is formatted in real time.

UnitInfo8+

Defines the measurement unit information.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

NameTypeReadableWritableDescription
unitstringYesYesName of the measurement unit, for example, meter, inch, or cup.
measureSystemstringYesYesMeasurement system. The value can be SI, US, or UK.

i18n.getInstance8+

getInstance(locale?: string): IndexUtil

Creates an IndexUtil object.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
localestringNoSystem locale, which consists of the language, script, and country/region.
The default value is the current system locale.

Return value

TypeDescription
IndexUtilIndexUtil object created based on the specified locale ID.

Example

let indexUtil: i18n.IndexUtil = i18n.getInstance('zh-CN');

IndexUtil8+

getIndexList8+

getIndexList(): Array<string>

Obtains the index list of the current locale.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Return value

TypeDescription
Array<string>Index list of the current locale. The first and last elements are ....

Example

let indexUtil: i18n.IndexUtil = i18n.getInstance('zh-CN');
// indexList = [ '...', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
//              'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '...' ]
let indexList: Array<string> = indexUtil.getIndexList();

addLocale8+

addLocale(locale: string): void

Adds the index list of a new locale to the index list of the current locale to form a composite list.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
localestringYesSystem locale, which consists of the language, script, and country/region.

Example

let indexUtil: i18n.IndexUtil = i18n.getInstance('zh-CN');
indexUtil.addLocale('en-US');

getIndex8+

getIndex(text: string): string

Obtains the index of the text object.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
textstringYestext object.

Return value

TypeDescription
stringIndex of the text object. If no proper index is found, an empty string is returned.

Example

let indexUtil: i18n.IndexUtil = i18n.getInstance('zh-CN');
let index: string = indexUtil.getIndex('hi'); // index = 'H'

i18n.getLineInstance8+

getLineInstance(locale: string): BreakIterator

Obtains a BreakIterator object. The BreakIterator object maintains an internal break iterator that can be used to access various line break points.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
localestringYesSystem locale, which consists of the language, script, and country/region.
The generated BreakIterator object calculates the positions of line breaks based on the rules of the specified locale.

Return value

TypeDescription
BreakIteratorBreakIterator object.

Example

let iterator: i18n.BreakIterator = i18n.getLineInstance('en');

BreakIterator8+

setLineBreakText8+

setLineBreakText(text: string): void

Sets the text to be processed by the BreakIterator object.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
textstringYesInput text.

Example

let iterator: i18n.BreakIterator = i18n.getLineInstance('en');
iterator.setLineBreakText('Apple is my favorite fruit.'); // Set the text to be processed.

getLineBreakText8+

getLineBreakText(): string

Obtains the text processed by the BreakIterator object.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Return value

TypeDescription
stringText being processed by the BreakIterator object.

Example

let iterator: i18n.BreakIterator = i18n.getLineInstance('en');
iterator.setLineBreakText('Apple is my favorite fruit.');
let breakText: string = iterator.getLineBreakText(); // breakText = 'Apple is my favorite fruit.'

current8+

current(): number

Obtains the position of the break iterator in the text.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Return value

TypeDescription
numberPosition of the break iterator in the text.

Example

let iterator: i18n.BreakIterator = i18n.getLineInstance('en');
iterator.setLineBreakText('Apple is my favorite fruit.');
let currentPos: number = iterator.current(); // currentPos = 0

first8+

first(): number

Moves the break iterator to the first line break point, which is always at the beginning of the processed text.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Return value

TypeDescription
numberOffset of the first line break point in the processed text.

Example

let iterator: i18n.BreakIterator = i18n.getLineInstance('en');
iterator.setLineBreakText('Apple is my favorite fruit.');
let firstPos: number = iterator.first(); // firstPos = 0

last8+

last(): number

Moves the break iterator to the last line break point, which is always the next position after the end of the processed text.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Return value

TypeDescription
numberOffset of the last line break point in the processed text.

Example

let iterator: i18n.BreakIterator = i18n.getLineInstance('en');
iterator.setLineBreakText('Apple is my favorite fruit.');
let lastPos: number = iterator.last(); // lastPos = 27

next8+

next(index?: number): number

Moves the break iterator backward by the specified number of line break points.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
indexnumberNoNumber of line break points for moving the break iterator. The value is an integer.
A positive number means to move the break iterator backward, and a negative number means to move the break iterator forward.
The default value is 1.

Return value

TypeDescription
numberPosition of the break iterator in the text after movement.
The value -1 is returned if the position of the break iterator is outside of the processed text after movement.

Example

let iterator: i18n.BreakIterator = i18n.getLineInstance('en');
iterator.setLineBreakText('Apple is my favorite fruit.');
let pos: number = iterator.first(); // pos = 0
pos = iterator.next(); // pos = 6
pos = iterator.next(10); // pos = -1

previous8+

previous(): number

Moves the break iterator foreward by one line break point.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Return value

TypeDescription
numberPosition of the break iterator in the text after movement.
The value -1 is returned if the position of the break iterator is outside of the processed text after movement.

Example

let iterator: i18n.BreakIterator = i18n.getLineInstance('en');
iterator.setLineBreakText('Apple is my favorite fruit.');
let pos: number = iterator.first(); // pos = 0
pos = iterator.next(3); // pos = 12
pos = iterator.previous(); // pos = 9

following8+

following(offset: number): number

Moves the line break iterator to the line break point after the specified position.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
offsetnumberYesOffset of the line break point.

Return value

TypeDescription
numberPosition of the break iterator in the text after movement. The value -1 is returned if the position of the break iterator is outside of the processed text after movement.

Example

let iterator: i18n.BreakIterator = i18n.getLineInstance('en');
iterator.setLineBreakText('Apple is my favorite fruit.');
let pos: number = iterator.following(0); // pos = 6
pos = iterator.following(100); // pos = -1
pos = iterator.current(); // pos = 27

isBoundary8+

isBoundary(offset: number): boolean

Checks whether the specified position is a line break point.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
offsetnumberYesSpecified position in the text.

Return value

TypeDescription
booleanWhether the specified position is a line break point. The value true indicates that the specified position is a line break point, and the value false indicates the opposite.
If true is returned, the break iterator is moved to the position specified by offset. Otherwise, the break iterator is moved to the text line break point after the position specified by offset, which is equivalent to calling following.

Example

let iterator: i18n.BreakIterator = i18n.getLineInstance('en');
iterator.setLineBreakText('Apple is my favorite fruit.');
let isBoundary: boolean = iterator.isBoundary(0); // isBoundary = true;
isBoundary = iterator.isBoundary(5); // isBoundary = false;

i18n.getTimeZone

getTimeZone(zoneID?: string): TimeZone

Obtains the TimeZone object corresponding to the specified time zone ID.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
zoneIDstringNoTime zone ID. The default value is the system time zone.

Return value

TypeDescription
TimeZoneTimeZone object corresponding to the time zone ID.

Example

let timezone: i18n.TimeZone = i18n.getTimeZone('Asia/Shanghai');

TimeZone

getID

getID(): string

Obtains the ID of the specified TimeZone object.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Return value

TypeDescription
stringTime zone ID corresponding to the TimeZone object.

Example

let timezone: i18n.TimeZone = i18n.getTimeZone('Asia/Shanghai');
let timezoneID: string = timezone.getID(); // timezoneID = 'Asia/Shanghai'

getDisplayName

getDisplayName(locale?: string, isDST?: boolean): string

Obtains time zone display name in the specified language.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
localestringNoSystem locale, which consists of the language, script, and country/region. The default value is the current system locale.
isDSTbooleanNoWhether DST information is displayed. The value true indicates that DST information is displayed, and the value false indicates the opposite. The default value is false.

Return value

TypeDescription
stringTime zone display name in the specified language.

Example

let timezone: i18n.TimeZone = i18n.getTimeZone('Asia/Shanghai');
let timezoneName: string = timezone.getDisplayName('zh-CN', false); // timezoneName = 'China Standard Time'

getRawOffset

getRawOffset(): number

Obtains the raw offset of the specified time zone.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Return value

TypeDescription
numberRaw offset of the time zone, in milliseconds.

Example

let timezone: i18n.TimeZone = i18n.getTimeZone('Asia/Shanghai');
let offset: number = timezone.getRawOffset(); // offset = 28800000

getOffset

getOffset(date?: number): number

Obtains the offset of the specified time zone at the specified time.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
datenumberNoSpecified time, in milliseconds. The default value is the system time.

Return value

TypeDescription
numberTime zone offset, in milliseconds. When the DST is used, the time zone offset is the raw time zone offset plus the DST offset.

Example

let timezone: i18n.TimeZone = i18n.getTimeZone('Asia/Shanghai');
let offset: number = timezone.getOffset(1234567890); // offset = 28800000

getAvailableIDs9+

static getAvailableIDs(): Array<string>

Obtains the list of time zone IDs supported by the system.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Return value

TypeDescription
Array<string>List of time zone IDs supported by the system.

Example

// ids = ['America/Adak', 'America/Anchorage', 'America/Bogota', 'America/Denver', 'America/Los_Angeles', 'America/Montevideo', 'America/Santiago', 'America/Sao_Paulo', 'Asia/Ashgabat', 'Asia/Hovd', 'Asia/Jerusalem', 'Asia/Magadan', 'Asia/Omsk', 'Asia/Shanghai', 'Asia/Tokyo', 'Asia/Yerevan', 'Atlantic/Cape_Verde', 'Australia/Lord_Howe', 'Europe/Dublin', 'Europe/London', 'Europe/Moscow', 'Pacific/Auckland', 'Pacific/Easter', 'Pacific/Pago-Pago']
let ids: Array<string> = i18n.TimeZone.getAvailableIDs();

getAvailableZoneCityIDs9+

static getAvailableZoneCityIDs(): Array<string>

Obtains the list of time zone city IDs supported by the system.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Return value

TypeDescription
Array<string>List of time zone city IDs supported by the system.

Example

// cityIDs = ['Auckland', 'Magadan', 'Lord Howe Island', 'Tokyo', 'Shanghai', 'Hovd', 'Omsk', 'Ashgabat', 'Yerevan', 'Moscow', 'Tel Aviv', 'Dublin', 'London', 'Praia', 'Montevideo', 'Brasília', 'Santiago', 'Bogotá', 'Easter Island', 'Salt Lake City', 'Los Angeles', 'Anchorage', 'Adak', 'Pago Pago']
let cityIDs: Array<string> = i18n.TimeZone.getAvailableZoneCityIDs();

getCityDisplayName9+

static getCityDisplayName(cityID: string, locale: string): string

Obtains time zone city display name in the specified language.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
cityIDstringYesTime zone city ID.
localestringYesSystem locale, which consists of the language, script, and country/region.

Return value

TypeDescription
stringTime zone city display name in the specified language.

Example

let displayName: string = i18n.TimeZone.getCityDisplayName('Shanghai', 'zh-CN'); // displayName = 'Shanghai (China)'

getTimezoneFromCity9+

static getTimezoneFromCity(cityID: string): TimeZone

Creates a TimeZone object corresponding to the specified time zone city.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
cityIDstringYesTime zone city ID. The value must be a time zone city ID supported by the system.

Return value

TypeDescription
TimeZoneTimeZone object corresponding to the specified time zone city ID.

Example

let timezone: i18n.TimeZone = i18n.TimeZone.getTimezoneFromCity('Shanghai');

getTimezonesByLocation10+

static getTimezonesByLocation(longitude: number, latitude: number): Array<TimeZone>

Creates an array of TimeZone objects corresponding to the specified location.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
longitudenumberYesLongitude. The value range is [-180, 179.9). A positive value is used for east longitude and a negative value is used for west longitude.
latitudenumberYesLatitude. The value range is [-90, 89.9). A positive value is used for north latitude and a negative value is used for south latitude.

Return value

TypeDescription
Array<TimeZone>TimeZone objects corresponding to the specified location.

Error codes

For details about the error codes, see ohos.i18n Error Codes and Universal Error Codes.

IDError Message
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.
890001Invalid parameter. Possible causes: Parameter verification failed.

Description

The error message of 890001 is subject to the actual error.

Example

import { BusinessError } from '@kit.BasicServicesKit';

try {
  let timezoneArray: Array<i18n.TimeZone> = i18n.TimeZone.getTimezonesByLocation(-118.1, 34.0);
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`call TimeZone.getTimezonesByLocation failed, error code: ${err.code}, message: ${err.message}.`);
}

Transliterator9+

getAvailableIDs9+

static getAvailableIDs(): string[]

Obtains a list of IDs supported by the Transliterator object.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Return value

TypeDescription
string[]List of IDs supported by the Transliterator object.

Example

// A total of 742 IDs are supported. One ID is comprised of two parts separated by a hyphen (-) in the format of source-destination. For example, in **ids = ["Han-Latin","Latin-ASCII", "Amharic-Latin/BGN","Accents-Any", ...]**, **Han-Latin** indicates conversion from Chinese to Latin, and **Amharic-Latin** indicates conversion from Amharic to Latin.
// For more information, see ISO-15924.
let ids: string[] = i18n.Transliterator.getAvailableIDs();

getInstance9+

static getInstance(id: string): Transliterator

Creates a Transliterator object based on the specified ID.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
idstringYesID supported by the Transliterator object.

Return value

TypeDescription
TransliteratorTransliterator object.

Example

let transliterator: i18n.Transliterator = i18n.Transliterator.getInstance('Any-Latn');

transform9+

transform(text: string): string

Converts the input text from the source format to the target format.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
textstringYestext object.

Return value

TypeDescription
stringText after conversion.

Example

let transliterator: i18n.Transliterator = i18n.Transliterator.getInstance('Any-Latn');
let wordArray = ['China', 'Germany', 'US', 'France"]
for (let i = 0; i < wordArray.length; i++) {
  let transliterLatn =
    transliterator.transform(wordArray[i]); // transliterLatn: 'zhōng guó', 'dé guó', 'měi guó', 'fǎ guó'
}

// Chinese transliteration and tone removal
let transliter = i18n.Transliterator.getInstance('Any-Latn;Latin-Ascii');
let transliterAscii = transliter.transform('中国'); // transliterAscii ='zhong guo'

// Chinese surname pronunciation
let nameTransliter = i18n.Transliterator.getInstance('Han-Latin/Names');
let transliterNames = nameTransliter.transform('单老师'); // transliterNames = 'shàn lǎo shī'
transliterNames = nameTransliter.transform('长孙无忌'); // transliterNames = 'zhǎng sūn wú jì'

Unicode9+

Atomic service API: This API can be used in atomic services since API version 12.

isDigit9+

static isDigit(char: string): boolean

Checks whether the input character is a digit.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
charstringYesInput character. If the input is a string, only the type of the first character is checked.

Return value

TypeDescription
booleantrue if the input character is a digit, and false otherwise.

Example

let isDigit: boolean = i18n.Unicode.isDigit('1'); // isDigit = true

isSpaceChar9+

static isSpaceChar(char: string): boolean

Checks whether the input character is a space.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
charstringYesInput character. If the input is a string, only the type of the first character is checked.

Return value

TypeDescription
booleantrue if the input character is a space, and false otherwise.

Example

let isSpacechar: boolean = i18n.Unicode.isSpaceChar('a'); // isSpacechar = false

isWhitespace9+

static isWhitespace(char: string): boolean

Checks whether the input character is a whitespace.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
charstringYesInput character. If the input is a string, only the type of the first character is checked.

Return value

TypeDescription
booleantrue if the input character is a white space, and false otherwise.

Example

let isWhitespace: boolean = i18n.Unicode.isWhitespace('a'); // isWhitespace = false

isRTL9+

static isRTL(char: string): boolean

Checks whether the input character is of the right to left (RTL) language.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
charstringYesInput character. If the input is a string, only the type of the first character is checked.

Return value

TypeDescription
booleantrue if the input character is of the RTL language, and false otherwise.

Example

let isRtl: boolean = i18n.Unicode.isRTL('a'); // isRtl = false

isIdeograph9+

static isIdeograph(char: string): boolean

Checks whether the input character is an ideographic character.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
charstringYesInput character. If the input is a string, only the type of the first character is checked.

Return value

TypeDescription
booleantrue if the input character an ideographic character, and false otherwise.

Example

let isIdeograph: boolean = i18n.Unicode.isIdeograph('a'); // isIdeograph = false

isLetter9+

static isLetter(char: string): boolean

Checks whether the input character is a letter.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
charstringYesInput character. If the input is a string, only the type of the first character is checked.

Return value

TypeDescription
booleantrue if the input character a letter, and false otherwise.

Example

let isLetter: boolean = i18n.Unicode.isLetter('a'); // isLetter = true

isLowerCase9+

static isLowerCase(char: string): boolean

Checks whether the input character is a lowercase letter.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
charstringYesInput character. If the input is a string, only the type of the first character is checked.

Return value

TypeDescription
booleantrue if the input character a lowercase letter, and false otherwise.

Example

let isLowercase: boolean = i18n.Unicode.isLowerCase('a'); // isLowercase = true

isUpperCase9+

static isUpperCase(char: string): boolean

Checks whether the input character is an uppercase letter.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
charstringYesInput character. If the input is a string, only the type of the first character is checked.

Return value

TypeDescription
booleantrue if the input character an uppercase letter, and false otherwise.

Example

let isUppercase: boolean = i18n.Unicode.isUpperCase('a'); // isUppercase = false

getType9+

static getType(char: string): string

Obtains the type of the input character.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
charstringYesInput character. If the input is a string, only the type of the first character is checked.

Return value

TypeDescription
stringType of the input character.

The following table lists only the common types. For more details, see the Unicode Standard.

NameValueDescription
U_UNASSIGNEDU_UNASSIGNEDNon-category for unassigned and non-character code points.
U_GENERAL_OTHER_TYPESU_GENERAL_OTHER_TYPESSame as U_UNASSIGNED.
U_UPPERCASE_LETTERU_UPPERCASE_LETTERUppercase letter.
U_LOWERCASE_LETTERU_LOWERCASE_LETTERLowercase letter.
U_TITLECASE_LETTERU_TITLECASE_LETTERTitle case letter.
U_MODIFIER_LETTERU_MODIFIER_LETTERModifier letter.
U_OTHER_LETTERU_OTHER_LETTERLetters other than the uppercase letter, lowercase letter, title case letter, and modifier letter.
U_NON_SPACING_MARKU_NON_SPACING_MARKNon-spacing mark, such as the accent symbol ' and the variable symbol #.
U_ENCLOSING_MARKU_ENCLOSING_MARKEnclosing mark, for example, a circle or a box.
U_COMBINING_SPACING_MARKU_COMBINING_SPACING_MARKSpacing mark, for example, the vowel symbol [].
U_DECIMAL_DIGIT_NUMBERU_DECIMAL_DIGIT_NUMBERDecimal number.
U_LETTER_NUMBERU_LETTER_NUMBERLetter and number (including Roman numeral).
U_OTHER_NUMBERU_OTHER_NUMBEROther numbers, which are used as encryption symbols, marker symbols, or non-Arabic numerals, such as @, #, (1), and .
U_SPACE_SEPARATORU_SPACE_SEPARATORSpace separator, for example, a space character, uninterrupted space character, or space character with a fixed width.
U_LINE_SEPARATORU_LINE_SEPARATORLine separator.
U_PARAGRAPH_SEPARATORU_PARAGRAPH_SEPARATORParagraph separator.
U_CONTROL_CHARU_CONTROL_CHARControl character.
U_FORMAT_CHARU_FORMAT_CHARFormat character.
U_PRIVATE_USE_CHARU_PRIVATE_USE_CHARPrivately used character, for example, a company logo.
U_SURROGATEU_SURROGATESurrogate, which is used to represent supplementary characters in UTF-16.
U_DASH_PUNCTUATIONU_DASH_PUNCTUATIONDash punctuation.
U_START_PUNCTUATIONU_START_PUNCTUATIONStart punctuation, for example, the left parenthesis.
U_END_PUNCTUATIONU_END_PUNCTUATIONEnd punctuation, for example, the right parenthesis.
U_INITIAL_PUNCTUATIONU_INITIAL_PUNCTUATIONInitial punctuation, for example, the left double quotation mark or left single quotation mark.
U_FINAL_PUNCTUATIONU_FINAL_PUNCTUATIONFinal punctuation, for example, the right double quotation mark or right single quotation mark.
U_CONNECTOR_PUNCTUATIONU_CONNECTOR_PUNCTUATIONConnector punctuation.
U_OTHER_PUNCTUATIONU_OTHER_PUNCTUATIONOther punctuations.
U_MATH_SYMBOLU_MATH_SYMBOLMathematical symbol.
U_CURRENCY_SYMBOLU_CURRENCY_SYMBOLCurrency symbol.
U_MODIFIER_SYMBOLU_MODIFIER_SYMBOLModifier symbol.
U_OTHER_SYMBOLU_OTHER_SYMBOLOther symbols.

Example

let unicodeType: string = i18n.Unicode.getType('a'); // unicodeType = 'U_LOWERCASE_LETTER'

I18NUtil9+

unitConvert9+

static unitConvert(fromUnit: UnitInfo, toUnit: UnitInfo, value: number, locale: string, style?: string): string

Converts one measurement unit into another and formats the unit based on the specified locale and style.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
fromUnitUnitInfoYesMeasurement unit to be converted.
toUnitUnitInfoYesMeasurement unit to be converted to.
valuenumberYesValue of the measurement unit to be converted.
localestringYesLocale ID, which consists of the language, script, and country/region, for example, zh-Hans-CN.
stylestringNoStyle used for formatting. The value can be long, short, or narrow. The default value is short.
For details about the meaning or display effect of different values, see Number and Unit of Measurement Formatting.

Return value

TypeDescription
stringString converted to the measurement unit after formatting.

Example

let fromUnit: i18n.UnitInfo = { unit: 'cup', measureSystem: 'US' };
let toUnit: i18n.UnitInfo = { unit: 'liter', measureSystem: 'SI' };
let convertResult: string =
  i18n.I18NUtil.unitConvert(fromUnit, toUnit, 1000, 'en-US', 'long'); // convertResult = '236.588 liters'

getDateOrder9+

static getDateOrder(locale: string): string

Obtains the sequence of the year, month, and day in the specified locale.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
localestringYesLocale ID, which consists of the language, script, and country/region, for example, zh-Hans-CN.

Return value

TypeDescription
stringSequence of the year, month, and day in the locale. y indicates the year, L indicates the month, and d indicates the day.

Example

let order: string = i18n.I18NUtil.getDateOrder('zh-CN'); // order = 'y-L-d'

getTimePeriodName11+

static getTimePeriodName(hour:number, locale?: string): string

Obtains the localized expression of the specified time in the specified locale.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
hournumberYesSpecified time, for example, 16.
localestringNoSystem locale, which consists of the language, script, and country/region. for example, zh-Hans-CN.
The default value is the current system locale.

Return value

TypeDescription
stringLocalized expression of the specified time in the specified locale.

Error codes

For details about the error codes, see ohos.i18n Error Codes and Universal Error Codes.

IDError Message
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.
890001Invalid parameter. Possible causes: Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';

try {
  let name: string = i18n.I18NUtil.getTimePeriodName(2, 'zh-CN'); // name = 'a.m.'
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`call I18NUtil.getTimePeriodName failed, error code: ${err.code}, message: ${err.message}.`);
}

getBestMatchLocale12+

static getBestMatchLocale(locale: string, localeList: string[]): string

Obtains the locale that best matches a region from the specified locale list.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
localestringYesLocale ID, for example, zh-Hans-CN.
localeListstring[]YesList of locale IDs.

Return value

TypeDescription
stringID of the locale that best matches a region. If no matching locale is found, an empty string is returned.

Error codes

For details about the error codes, see ohos.i18n Error Codes and Universal Error Codes.

IDError Message
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.
890001Invalid parameter. Possible causes: Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';

try {
  let matchedLocaleId: string = i18n.I18NUtil.getBestMatchLocale('zh-Hans-CN',
    ['en-Latn-US', 'en-GB', 'zh-Hant-CN', 'zh-Hans-MO']); // matchedLocaleId = 'zh-Hans-MO'
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`call I18NUtil.getBestMatchLocale failed, error code: ${err.code}, message: ${err.message}.`);
}

getThreeLetterLanguage12+

static getThreeLetterLanguage(locale: string): string

Converts a language code from two letters to three letters.
For example, the two-letter language code of Chinese is zh, and the corresponding three-letter language code is zho. For details, see ISO 639.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
localestringYesTwo-letter code of the language to be converted, for example, zh.

Return value

TypeDescription
stringLanguage code after conversion.

Error codes

For details about the error codes, see ohos.i18n Error Codes and Universal Error Codes.

IDError Message
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.
890001Invalid parameter. Possible causes: Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';

try {
  let language: string = i18n.I18NUtil.getThreeLetterLanguage('zh') // language = 'zho'
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`call I18NUtil.getThreeLetterLanguage failed, error code: ${err.code}, message: ${err.message}.`);
}

getThreeLetterRegion12+

static getThreeLetterRegion(locale: string): string

Converts a region code from two letters to three letters.
For example, the two-letter region code of China is CN, and the corresponding three-letter region code is CHN. For details, see ISO 3166.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
localestringYesTwo-letter country/region code to be converted, for example, CN.

Return value

TypeDescription
stringRegion code after conversion .

Error codes

For details about the error codes, see ohos.i18n Error Codes and Universal Error Codes.

IDError Message
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.
890001Invalid parameter. Possible causes: Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';

try {
  let region: string = i18n.I18NUtil.getThreeLetterRegion('CN') // region = 'CHN'
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`call I18NUtil.getThreeLetterRegion failed, error code: ${err.code}, message: ${err.message}.`);
}

getUnicodeWrappedFilePath18+

static getUnicodeWrappedFilePath(path: string, delimiter?: string, locale?: intl.Locale): string

Localizes a file path for the specified locale.
For example, /data/out/tmp is changed to tmp/out/data/ after localization.

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
pathstringYesPath to mirror, for example, /data/out/tmp.
delimiterstringNoPath delimiter. The default value is /.
localeintl.LocaleNoLocale object. The default value is the current system locale.

Return value

TypeDescription
stringFile path after localization. If the specified locale object corresponds to an RTL language, the processed file path contains a direction control character to ensure that the file path is displayed in mirror mode.

Error codes

For details about the error codes, see i18n Error Codes.

IDError Message
890001Invalid parameter. Possible causes: Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { intl } from '@kit.LocalizationKit';

try {
  let path: string = '/data/out/tmp';
  let delimiter: string = '/';
  let locale: intl.Locale = new intl.Locale('ar');
  let mirrorPath: string =
    i18n.I18NUtil.getUnicodeWrappedFilePath(path, delimiter, locale); // mirrorPath is displayed as tmp/out/data/.
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`call I18NUtil.getUnicodeWrappedFilePath failed, error code: ${err.code}, message: ${err.message}.`);
}

Normalizer10+

getInstance10+

static getInstance(mode: NormalizerMode): Normalizer

Obtains a Normalizer object.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
modeNormalizerModeYesText normalization mode.

Return value

TypeDescription
NormalizerNormalizer object for text normalization.

Error codes

For details about the error codes, see Universal Error Codes.

IDError Message
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.

Example

import { BusinessError } from '@kit.BasicServicesKit';

try {
  let normalizer: i18n.Normalizer = i18n.Normalizer.getInstance(i18n.NormalizerMode.NFC);
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`call Normalizer.getInstance failed, error code: ${err.code}, message: ${err.message}.`);
}

normalize10+

normalize(text: string): string

Normalizes input strings.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
textstringYestext object.

Return value

TypeDescription
stringNormalized strings.

Error codes

For details about the error codes, see Universal Error Codes.

IDError Message
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.

Example

import { BusinessError } from '@kit.BasicServicesKit';

try {
  let normalizer: i18n.Normalizer = i18n.Normalizer.getInstance(i18n.NormalizerMode.NFC);
  let normalizedText: string = normalizer.normalize('\u1E9B\u0323'); // normalizedText = 'ẛ̣'
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`call Normalizer.getInstance failed, error code: ${err.code}, message: ${err.message}.`);
}

NormalizerMode10+

Enumerates text normalization modes.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

NameValueDescription
NFC1NFC.
NFD2NFD.
NFKC3NFKC.
NFKD4NFKD.

HolidayManager11+

constructor11+

constructor(icsPath: String)

Creates a HolidayManager object for parsing holiday data.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
icsPathStringYesPath of the .ics file with the read permission granted for applications.

Error codes

For details about the error codes, see ohos.i18n Error Codes and Universal Error Codes.

IDError Message
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.
890001Invalid parameter. Possible causes: Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';

try {
  let holidayManager = new i18n.HolidayManager('/system/lib/US.ics');
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`call i18n.HolidayManager failed, error code: ${err.code}, message: ${err.message}.`);
}

isHoliday11+

isHoliday(date?: Date): boolean

Determines whether the specified date is a holiday.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
dateDateNoDate and time. Note: The month starts from 0. For example, 0 indicates January.
The default value is the current date.

Return value

TypeDescription
booleantrue if the specified date is a holiday, and false otherwise.

Error codes

For details about the error codes, see Universal Error Codes.

IDError Message
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.

Example

import { BusinessError } from '@kit.BasicServicesKit';

try {
  // Replace /system/lib/US.ics with the actual ICS file path.
  let holidayManager: i18n.HolidayManager = new i18n.HolidayManager('/system/lib/US.ics');
  let isHoliday: boolean = holidayManager.isHoliday();
  isHoliday = holidayManager.isHoliday(new Date(2023, 5, 25)); // The date is 2023.06.25.
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`call holidayManager.isHoliday failed, error code: ${err.code}, message: ${err.message}.`);
}

getHolidayInfoItemArray11+

getHolidayInfoItemArray(year?: number): Array<HolidayInfoItem>

Obtains the holiday information list of the specified year.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
yearnumberNoSpecified year, for example, 2023.
The default value is the current year.

Return value

TypeDescription
Array<HolidayInfoItem>Holiday information list.

Error codes

For details about the error codes, see ohos.i18n Error Codes and Universal Error Codes.

IDError Message
401Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.
890001Invalid parameter. Possible causes: Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';

try {
  // Replace /system/lib/US.ics with the actual ICS file path.
  let holidayManager: i18n.HolidayManager = new i18n.HolidayManager('/system/lib/US.ics');
  let holidayInfoItemArray: Array<i18n.HolidayInfoItem> = holidayManager.getHolidayInfoItemArray(2023);
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`call holidayManager.getHolidayInfoItemArray failed, error code: ${err.code}, message: ${err.message}.`);
}

HolidayInfoItem11+

Represents the holiday information.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

NameTypeMandatoryDescription
baseNamestringYesHoliday name.
yearnumberYesYear of the holiday.
monthnumberYesMonth of the holiday.
daynumberYesDay of the holiday.
localNamesArray<HolidayLocalName>NoLocal names of the holiday.

HolidayLocalName11+

Represents the name of a holiday in different languages.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Global.I18n

NameTypeMandatoryDescription
languagestringYesLanguage, for example, ar, en, or tr.
namestringYesLocal name of a holiday. For example, the Turkish name of Sacrifice Feast is Kurban Bayrami.

i18n.getSimpleDateTimeFormatByPattern18+

getSimpleDateTimeFormatByPattern(pattern: string, locale?: intl.Locale): SimpleDateTimeFormat

Obtains a SimpleDateTimeFormat object based on the specified pattern string. For details about the display differences between the objects obtained by this API and getSimpleDateTimeFormatBySkeleton, see [SimpleDateTimeFormat] (#simpledatetimeformat18).

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
patternstringYesValid pattern. For details about the supported characters and their meanings, see Date Field Symbol Table. This parameter also supports custom text enclosed in single quotation marks ('').
localeintl.LocaleNoLocale object. The default value is the current system locale.

Return value

TypeDescription
SimpleDateTimeFormatSimpleDateTimeFormat object.

Error codes

For details about the error codes, see i18n Error Codes.

IDError Message
890001Invalid parameter. Possible causes: Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { intl } from '@kit.LocalizationKit';

try {
  let locale: intl.Locale = new intl.Locale('zh-Hans-CN');
  let formatter: i18n.SimpleDateTimeFormat = i18n.getSimpleDateTimeFormatByPattern("'month('M')'", locale);
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`call i18n.getSimpleDateTimeFormatByPattern failed, error code: ${err.code}, message: ${err.message}.`);
}

i18n.getSimpleDateTimeFormatBySkeleton18+

getSimpleDateTimeFormatBySkeleton(skeleton: string, locale?: intl.Locale): SimpleDateTimeFormat

Obtains a SimpleDateTimeFormat object based on the specified skeleton. For details about the display differences between the objects obtained by this API and getSimpleDateTimeFormatByPattern, see [SimpleDateTimeFormat] (#simpledatetimeformat18).

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
skeletonstringYesValid skeleton. For details about the supported characters and their meanings, see Date Field Symbol Table. This parameter does not support custom text.
localeintl.LocaleNoLocale object. The default value is the current system locale.

Return value

TypeDescription
SimpleDateTimeFormatSimpleDateTimeFormat object.

Error codes

For details about the error codes, see i18n Error Codes.

IDError Message
890001Invalid parameter. Possible causes: Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { intl } from '@kit.LocalizationKit';

try {
  let locale: intl.Locale = new intl.Locale('zh-Hans-CN');
  let formatter: i18n.SimpleDateTimeFormat = i18n.getSimpleDateTimeFormatBySkeleton('yMd', locale);
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`call i18n.getSimpleDateTimeFormatBySkeleton failed, error code: ${err.code}, message: ${err.message}.`);
}

SimpleDateTimeFormat18+

format18+

format(date: Date): string

Formats the date and time.

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
dateDateYesDate and time. Note: The month starts from 0. For example, 0 indicates January.

Return value

TypeDescription
stringA string containing the formatted date and time.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { intl } from '@kit.LocalizationKit';

try {
  let locale : intl.Locale = new intl.Locale("zh-Hans-CN");
  let date: Date = new Date(2024, 11, 13); // Set the date to 2024.12.13.

  let formatterWithText: i18n.SimpleDateTimeFormat =
    i18n.getSimpleDateTimeFormatByPattern("'month('M')'", locale);
  let formattedDate: string = formatterWithText.format(date); // formattedDate = 'month(12)'

  let patternFormatter: i18n.SimpleDateTimeFormat = i18n.getSimpleDateTimeFormatByPattern('yMd', locale);
  formattedDate = patternFormatter.format(date); // formattedDate = '20241213'

  let skeletonFormatter: i18n.SimpleDateTimeFormat = i18n.getSimpleDateTimeFormatBySkeleton('yMd', locale);
  formattedDate = skeletonFormatter.format(date); // formattedDate = '2024/12/13'
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`call SimpleDateTimeFormat.format failed, error code: ${err.code}, message: ${err.message}.`);
}

i18n.getSimpleNumberFormatBySkeleton18+

getSimpleNumberFormatBySkeleton(skeleton: string, locale?: intl.Locale): SimpleNumberFormat

Obtains a SimpleNumberFormat object based on the specified skeleton.

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
skeletonstringYesValid skeleton. For details about the supported characters and their meanings, see Number Skeletons.
localeintl.LocaleNoLocale object. The default value is the current system locale.

Return value

TypeDescription
SimpleNumberFormatSimpleNumberFormat object.

Error codes

For details about the error codes, see i18n Error Codes.

IDError Message
890001Invalid parameter. Possible causes: Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { intl } from '@kit.LocalizationKit';

try {
  let locale: intl.Locale = new intl.Locale('zh-Hans-CN');
  let formatter: i18n.SimpleNumberFormat = i18n.getSimpleNumberFormatBySkeleton('%', locale);
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`call SimpleDateTimeFormat.getSimpleNumberFormatBySkeleton failed, error code: ${err.code}, message: ${err.message}.`);
}

SimpleNumberFormat18+

format18+

format(value: number): string

Formats a number.

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
valuenumberYesNumber to be formatted.

Return value

TypeDescription
stringFormatted number.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { intl } from '@kit.LocalizationKit';

try {
  let locale: intl.Locale = new intl.Locale('zh-Hans-CN');
  let formatter: i18n.SimpleNumberFormat = i18n.getSimpleNumberFormatBySkeleton('%', locale);
  let formattedNumber: string = formatter.format(10); // formattedNumber = '10%'
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`call SimpleNumberFormat.format failed, error code: ${err.code}, message: ${err.message}.`);
}

StyledNumberFormat18+

constructor18+

constructor(numberFormat: intl.NumberFormat|SimpleNumberFormat, options?: StyledNumberFormatOptions)

Creates a NumberFormat object for rich text display.

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
numberFormatintl.NumberFormat |SimpleNumberFormatYesNumberFormat object.
optionsStyledNumberFormatOptionsNoConfiguration options of the NumberFormat object. The default value is the default text style.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { intl } from '@kit.LocalizationKit';

try {
  let integerTextStyle: TextStyle = new TextStyle({ fontColor: Color.Red });
  let decimalTextStyle: TextStyle = new TextStyle({ fontColor: Color.Brown });
  let fractionTextStyle: TextStyle = new TextStyle({ fontColor: Color.Blue });
  let unitTextStyle: TextStyle = new TextStyle({ fontColor: Color.Green });

  // Create a StyledNumberFormat object through intl.NumberFormat.
  let numFmt: intl.NumberFormat = new intl.NumberFormat('zh', { style: 'unit', unit: 'percent' });
  let styledNumFmt: i18n.StyledNumberFormat = new i18n.StyledNumberFormat(numFmt, {
    integer: integerTextStyle,
    decimal: decimalTextStyle,
    fraction: fractionTextStyle,
    unit: unitTextStyle
  });

  // Create a StyledNumberFormat object through SimpleNumberFormat.
  let locale: intl.Locale = new intl.Locale('zh');
  let simpleNumFmt: i18n.SimpleNumberFormat = i18n.getSimpleNumberFormatBySkeleton('percent', locale);
  let styledSimpleNumFmt: i18n.StyledNumberFormat = new i18n.StyledNumberFormat(simpleNumFmt, {
    integer: integerTextStyle,
    decimal: decimalTextStyle,
    fraction: fractionTextStyle,
    unit: unitTextStyle
  });
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`call i18n.StyledNumberFormat failed, error code: ${err.code}, message: ${err.message}.`);
}

format18+

format(value: number): StyledString

Formats a number as a rich text object.

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
valuenumberYesNumber to be formatted.

Return value

TypeDescription
StyledStringRich text object after formatting.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { intl } from '@kit.LocalizationKit';

try {
  let integerTextStyle: TextStyle = new TextStyle({ fontColor: Color.Red });
  let decimalTextStyle: TextStyle = new TextStyle({ fontColor: Color.Brown });
  let fractionTextStyle: TextStyle = new TextStyle({ fontColor: Color.Blue });
  let unitTextStyle: TextStyle = new TextStyle({ fontColor: Color.Green });

  // Create a StyledNumberFormat object through intl.NumberFormat.
  let numFmt: intl.NumberFormat = new intl.NumberFormat('zh', { style: 'unit', unit: 'percent' });
  let styledNumFmt: i18n.StyledNumberFormat = new i18n.StyledNumberFormat(numFmt, {
    integer: integerTextStyle,
    decimal: decimalTextStyle,
    fraction: fractionTextStyle,
    unit: unitTextStyle
  });
  // formattedNumber.getString () is 1,234.568%. In the formatted number, 1,234 is in red, . in brown, 568 in blue, and % in green.
  let formattedNumber: StyledString = styledNumFmt.format(1234.5678);

  // Create a StyledNumberFormat object through SimpleNumberFormat.
  let locale: intl.Locale = new intl.Locale('zh');
  let simpleNumFmt: i18n.SimpleNumberFormat = i18n.getSimpleNumberFormatBySkeleton('percent', locale);
  let styledSimpleNumFmt: i18n.StyledNumberFormat = new i18n.StyledNumberFormat(simpleNumFmt, {
    integer: integerTextStyle,
    decimal: decimalTextStyle,
    fraction: fractionTextStyle,
    unit: unitTextStyle
  });
  // formattedSimpleNumber.getString () is 1,234.5678%. In the formatted number, '1,234' is in red, . in brown, 5678 in blue, and % in green.
  let formattedSimpleNumber: StyledString = styledSimpleNumFmt.format(1234.5678);
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`call StyledNumberFormat.format failed, error code: ${err.code}, message: ${err.message}.`);
}

StyledNumberFormatOptions18+

Represents optional configuration items for the NumberFormat object.

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.Global.I18n

NameTypeMandatoryDescription
integerTextStyleNoText style for the integer part. The default value is the default text style.
decimalTextStyleNoText style for the decimal point. The default value is the default text style.
fractionTextStyleNoText style for the fraction part. The default value is the default text style.
unitTextStyleNoText style for the unit. The default value is the default text style.

i18n.getDisplayCountry(deprecated)

getDisplayCountry(country: string, locale: string, sentenceCase?: boolean): string

Obtains the localized name of the specified country/region.

This API is deprecated since API version 9. You are advised to use System.getDisplayCountry.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
countrystringYesSpecified country.
localestringYesSystem locale, which consists of the language, script, and country/region.
sentenceCasebooleanNoWhether to use sentence case to display the text. The value true means to display the text in title case format, and the value false means to display the text in the default case format of the locale. The default value is true.

Return value

TypeDescription
stringLocalized script for the specified country.

Example

let countryName: string = i18n.getDisplayCountry('zh-CN', 'en-GB', true); // countryName = 'China'
countryName = i18n.getDisplayCountry('zh-CN', 'en-GB'); // countryName = 'China'

i18n.getDisplayLanguage(deprecated)

getDisplayLanguage(language: string, locale: string, sentenceCase?: boolean): string

Obtains the localized script for the specified language.

This API is deprecated since API version 9. You are advised to use System.getDisplayLanguage.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
languagestringYesSpecified language.
localestringYesSystem locale, which consists of the language, script, and country/region.
sentenceCasebooleanNoWhether to use sentence case to display the text. The value true means to display the text in title case format, and the value false means to display the text in the default case format of the locale. The default value is true.

Return value

TypeDescription
stringLocalized script for the specified language.

Example

let languageName: string = i18n.getDisplayLanguage('zh', 'en-GB', true); // languageName = 'Chinese'
languageName = i18n.getDisplayLanguage('zh', 'en-GB'); // languageName = 'Chinese'

i18n.getSystemLanguage(deprecated)

getSystemLanguage(): string

Obtains the system language.

This API is deprecated since API version 9. You are advised to use System.getSystemLanguage.

System capability: SystemCapability.Global.I18n

Return value

TypeDescription
stringSystem language ID.

Example

let systemLanguage: string = i18n.getSystemLanguage();

i18n.getSystemRegion(deprecated)

getSystemRegion(): string

Obtains the system region.

This API is deprecated since API version 9. You are advised to use System.getSystemRegion.

System capability: SystemCapability.Global.I18n

Return value

TypeDescription
stringSystem region ID.

Example

let region: string = i18n.getSystemRegion();

i18n.getSystemLocale(deprecated)

getSystemLocale(): string

Obtains the system locale.

This API is deprecated since API version 9. You are advised to use System.getSystemLocale.

System capability: SystemCapability.Global.I18n

Return value

TypeDescription
stringSystem locale ID.

Example

let locale: string = i18n.getSystemLocale();

i18n.is24HourClock(deprecated)

is24HourClock(): boolean

Checks whether the 24-hour clock is used.

This API is deprecated since API version 9. You are advised to use System.is24HourClock.

System capability: SystemCapability.Global.I18n

Return value

TypeDescription
booleantrue if the 24-hour clock is used, and false otherwise.

Example

let is24HourClock: boolean = i18n.is24HourClock();

i18n.set24HourClock(deprecated)

set24HourClock(option: boolean): boolean

Sets the 24-hour clock.

This API is deprecated since API version 9. The substitute API is available only for system applications.

Permission required: ohos.permission.UPDATE_CONFIGURATION

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
optionbooleanYesWhether to enable the 24-hour clock. The value true means to enable the 24-hour clock, and the value false means the opposite.

Return value

TypeDescription
booleantrue if the setting is successful, and false otherwise.

Example

// Set the system time to the 24-hour clock.
let success: boolean = i18n.set24HourClock(true);

i18n.addPreferredLanguage(deprecated)

addPreferredLanguage(language: string, index?: number): boolean

Adds a preferred language to the specified position on the preferred language list.

This API is supported since API version 8 and is deprecated since API version 9. The substitute API is available only for system applications.

Permission required: ohos.permission.UPDATE_CONFIGURATION

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
languagestringYesPreferred language to add.
indexnumberNoPosition to which the preferred language is added. The default value is the length of the preferred language list.

Return value

TypeDescription
booleantrue if the operation is successful, and false otherwise.

Example

// Add zh-CN to the preferred language list.
let language: string = 'zh-CN';
let index: number = 0;
let success: boolean = i18n.addPreferredLanguage(language, index);

i18n.removePreferredLanguage(deprecated)

removePreferredLanguage(index: number): boolean

Removes a preferred language from the specified position on the preferred language list.

This API is supported since API version 8 and is deprecated since API version 9. The substitute API is available only for system applications.

Permission required: ohos.permission.UPDATE_CONFIGURATION

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
indexnumberYesPosition of the preferred language to delete.

Return value

TypeDescription
booleanWhether the operation is successful. The value true indicates that the operation is successful, and the value false indicates the opposite.

Example

// Delete the first preferred language from the preferred language list.
let index: number = 0;
let success: boolean = i18n.removePreferredLanguage(index);

i18n.getPreferredLanguageList(deprecated)

getPreferredLanguageList(): Array<string>

Obtains the list of preferred languages.

This API is supported since API version 8 and is deprecated since API version 9. You are advised to use System.getPreferredLanguageList.

System capability: SystemCapability.Global.I18n

Return value

TypeDescription
Array<string>List of preferred languages.

Example

let preferredLanguageList: Array<string> = i18n.getPreferredLanguageList();

i18n.getFirstPreferredLanguage(deprecated)

getFirstPreferredLanguage(): string

Obtains the first language in the preferred language list.

This API is supported since API version 8 and is deprecated since API version 9. You are advised to use System.getFirstPreferredLanguage.

System capability: SystemCapability.Global.I18n

Return value

TypeDescription
stringFirst language in the preferred language list.

Example

let firstPreferredLanguage: string = i18n.getFirstPreferredLanguage();

Util(deprecated)

unitConvert(deprecated)

unitConvert(fromUnit: UnitInfo, toUnit: UnitInfo, value: number, locale: string, style?: string): string

Converts one measurement unit into another and formats the unit based on the specified locale and style.

This API is supported since API version 8 and is deprecated since API version 9. You are advised to use unitConvert.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
fromUnitUnitInfoYesMeasurement unit to be converted.
toUnitUnitInfoYesMeasurement unit to be converted to.
valuenumberYesValue of the measurement unit to be converted.
localestringYesLocale ID used for formatting, for example, zh-Hans-CN.
stylestringNoStyle used for formatting. The value can be long, short, or narrow. The default value is short.

Return value

TypeDescription
stringString obtained after formatting based on the measurement unit specified by toUnit.

Character(deprecated)

isDigit(deprecated)

isDigit(char: string): boolean

Checks whether the input character is a digit.

This API is supported since API version 8 and is deprecated since API version 9. You are advised to use isDigit.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
charstringYesInput character. If the input is a string, only the type of the first character is checked.

Return value

TypeDescription
booleantrue if the input character is a digit, and false otherwise.

isSpaceChar(deprecated)

isSpaceChar(char: string): boolean

Checks whether the input character is a space.

This API is supported since API version 8 and is deprecated since API version 9. You are advised to use isSpaceChar.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
charstringYesInput character. If the input is a string, only the type of the first character is checked.

Return value

TypeDescription
booleantrue if the input character is a space, and false otherwise.

isWhitespace(deprecated)

isWhitespace(char: string): boolean

Checks whether the input character is a whitespace.

This API is supported since API version 8 and is deprecated since API version 9. You are advised to use isWhitespace.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
charstringYesInput character. If the input is a string, only the type of the first character is checked.

Return value

TypeDescription
booleantrue if the input character is a white space, and false otherwise.

isRTL(deprecated)

isRTL(char: string): boolean

Checks whether the input character is of the right to left (RTL) language.

This API is supported since API version 8 and is deprecated since API version 9. You are advised to use isRTL.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
charstringYesInput character. If the input is a string, only the type of the first character is checked.

Return value

TypeDescription
booleantrue if the input character is of the RTL language, and false otherwise.

isIdeograph(deprecated)

isIdeograph(char: string): boolean

Checks whether the input character is an ideographic character.

This API is supported since API version 8 and is deprecated since API version 9. You are advised to use isIdeograph.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
charstringYesInput character. If the input is a string, only the type of the first character is checked.

Return value

TypeDescription
booleantrue if the input character an ideographic character, and false otherwise.

isLetter(deprecated)

isLetter(char: string): boolean

Checks whether the input character is a letter.

This API is supported since API version 8 and is deprecated since API version 9. You are advised to use isLetter.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
charstringYesInput character. If the input is a string, only the type of the first character is checked.

Return value

TypeDescription
booleantrue if the input character a letter, and false otherwise.

isLowerCase(deprecated)

isLowerCase(char: string): boolean

Checks whether the input character is a lowercase letter.

This API is supported since API version 8 and is deprecated since API version 9. You are advised to use isLowerCase.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
charstringYesInput character. If the input is a string, only the type of the first character is checked.

Return value

TypeDescription
booleantrue if the input character a lowercase letter, and false otherwise.

isUpperCase(deprecated)

isUpperCase(char: string): boolean

Checks whether the input character is an uppercase letter.

This API is supported since API version 8 and is deprecated since API version 9. You are advised to use isUpperCase.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
charstringYesInput character. If the input is a string, only the type of the first character is checked.

Return value

TypeDescription
booleantrue if the input character an uppercase letter, and false otherwise.

getType(deprecated)

getType(char: string): string

Obtains the type of the input character.

This API is supported since API version 8 and is deprecated since API version 9. You are advised to use getType.

System capability: SystemCapability.Global.I18n

Parameters

NameTypeMandatoryDescription
charstringYesInput character. If the input is a string, only the type of the first character is checked.

Return value

TypeDescription
stringType of the input character.

你可能感兴趣的鸿蒙文章

harmony 鸿蒙Localization Kit

harmony 鸿蒙RawFileDescriptor

harmony 鸿蒙RawFileDescriptor64

harmony 鸿蒙ResourceManager_Configuration

harmony 鸿蒙Font Management Error Codes

harmony 鸿蒙I18N Error Codes

harmony 鸿蒙Resource Manager Error Codes

harmony 鸿蒙@ohos.fontManager (Font Management)

harmony 鸿蒙@ohos.i18n (Internationalization) (System API)

harmony 鸿蒙@ohos.intl (Internationalization)

  • 所属分类: 后端技术
  • 本文标签: 软件 鸿蒙
  • 版权声明: 本文链接 https://seaxiang.com/blog/XBJKED