Internationalization of HarmonyOS Next Applications: Calendar and Calendar System Handling

xun_wang_6384a403f9817c2

SameX

Posted on November 14, 2024

Internationalization of HarmonyOS Next Applications: Calendar and Calendar System Handling

This article aims to conduct an in-depth exploration of the technical details regarding calendar and calendar system handling in the application internationalization of Huawei's HarmonyOS Next system (up to API 12 currently), summarizing based on actual development practices. Mainly serving as a vehicle for technical sharing and communication, it is inevitable that there may be errors and omissions. Colleagues are welcomed to put forward valuable opinions and questions so that we can make progress together. This article is original content, and any form of reprinting must indicate the source and the original author.
In global application development, correct handling of calendars and calendar systems is an important aspect to meet the needs of users in different regions. The HarmonyOS Next system provides powerful calendar and calendar system handling functions, enabling applications to adapt to the time management habits of various cultures and regions. This article will introduce in detail the types of calendars supported by HarmonyOS Next applications, how to set up and apply different calendars, as well as methods for handling time and dates under different calendar systems, and discuss common problems and solutions, hoping to serve as a starting point for further discussion.

I. Types of Calendars Supported by HarmonyOS Next Applications

(I) Gregorian Calendar (Gregory)

  1. Features and Application Range     - The Gregorian calendar is the currently commonly used calendar system in the world, widely applied in most countries and regions globally. It takes the year of the birth of Jesus as the first year. A common year has 365 days, and a leap year has 366 days. The rule for determining a leap year is that a year divisible by 4 but not by 100 is a leap year, and in addition, a year divisible by 400 is also a leap year. The month and date settings in the Gregorian calendar are relatively regular. A year is divided into 12 months, and the number of days in each month is relatively fixed (except for February). In numerous fields such as business, science, and daily life, the Gregorian calendar is the main time measurement standard.
  2. Representation and Use in HarmonyOS Next Applications     - In HarmonyOS applications, when obtaining the system default calendar or without specifying a specific calendar, the Gregorian calendar is usually used for time and date handling. For example, in functions such as displaying the current date and arranging schedule reminders, the Gregorian calendar format is used by default. Developers can obtain a Gregorian calendar object through the i18n.getCalendar() method and then use this object for date setting, retrieval, and other operations. ### (II) Chinese Lunar Calendar (Chinese)
  3. Features and Application Range     - The Chinese lunar calendar is the traditional calendar of China and is also used to some extent in some countries and regions in East Asia (such as South Korea, Vietnam, etc.). The Chinese lunar calendar is a lunisolar calendar. It takes the cycle of the moon's phases as a month, and a year is divided into 12 months or 13 months (leap month). The years in the Chinese lunar calendar are represented by the Heavenly Stems and Earthly Branches chronology method, and a cycle of Heavenly Stems and Earthly Branches is 60 years. The Chinese lunar calendar is closely related to agricultural production and traditional festivals (such as the Spring Festival, Mid-Autumn Festival, etc.), and holds an important position in cultural inheritance and folk custom activities.
  4. Representation and Use in HarmonyOS Next Applications     - The HarmonyOS system provides support for the Chinese lunar calendar. Developers can obtain a Chinese lunar calendar object by specifying "chinese" as the calendar type. For example, when developing applications related to traditional Chinese culture (such as lunar calendar applications, festival reminder applications, etc.), the Chinese lunar calendar object can be used to obtain lunar date, solar terms, and other information. The lunar year (represented by Heavenly Stems and Earthly Branches), month, date, etc. can be obtained through the methods of the Chinese lunar calendar object, facilitating the application to display information related to the Chinese lunar calendar. ### (III) Other Calendar Types
  5. Buddhist Calendar (Buddhist)     - The Buddhist calendar is the calendar system used in some Buddhist countries and regions, taking the year after the Nirvana of Sakyamuni as the first year. It has a certain conversion relationship with the Gregorian calendar and may be used in some applications related to Buddhist culture (such as temple activity arrangements, Buddhist festival reminders, etc.). Developers can obtain a Buddhist calendar object by specifying "buddhist" and perform corresponding time and date handling.
  6. Islamic Calendar (Islamic_civil, Islamic_tbla, Islamic_umalqu, etc.)     - The Islamic calendar is the calendar system used in Islamic countries and regions and has multiple types, such as the Hijri calendar. The Islamic calendar takes the waxing and waning of the moon as the calculation unit, and a year is approximately 354 days or 355 days, which is quite different from the Gregorian calendar. In application scenarios involving Muslim religious activities and Ramadan calculations, the Islamic calendar needs to be used. Developers can select the appropriate Islamic calendar type (such as "islamic_civil", etc.) according to specific requirements to obtain a calendar object and perform relevant time handling.
  7. Indian Calendar (Indian), Japanese Calendar (Japanese), Persian Calendar (Persian), etc.     - These calendar systems have specific application scenarios in their respective countries and regions. For example, the Indian calendar plays an important role in religious ceremonies and festival arrangements in India; the Japanese calendar is still used in some traditional activities and cultural customs in Japan; the Persian calendar has certain applications in countries such as Iran. When developers are developing applications targeting these regions or related to these cultures, they may need to use the corresponding calendar types to accurately handle time and date information. ## II. Setting up and Applying Different Calendars ### (I) Obtaining Calendar Objects
  8. Obtaining According to Specified Types     - Developers can use the i18n.getCalendar() method and pass in the corresponding calendar type identifiers (such as "zh - Hans" representing the language and region, "gregory" representing the Gregorian calendar) to obtain a calendar object of a specific type. For example:
import { i18n } from '@kit.LocalizationKit';
let gregorianCalendar = i18n.getCalendar("zh - Hans", "gregory"); // Obtain the Gregorian calendar object in the Chinese environment
let lunarCalendar = i18n.getCalendar("zh - Hans", "chinese"); // Obtain the Chinese lunar calendar object in the Chinese environment
Enter fullscreen mode Exit fullscreen mode
  1. Obtaining According to System Default     - If the calendar type is not specified and the i18n.getCalendar() method is directly called, the system default calendar object will be obtained, which is usually the commonly used calendar type corresponding to the region set by the user's device (such as the Gregorian calendar in most regions). ### (II) Setting Calendar Properties
  2. Date Setting     - The setTime() or set() methods of the calendar object can be used to set the date of the calendar. The setTime() method can accept a Date object or a timestamp as a parameter for precisely setting the time point of the calendar. For example:
let calendar = i18n.getCalendar("zh - Hans", "gregory");
calendar.setTime(new Date(2023, 9, 15)); // Set the date of the Gregorian calendar object to October 15, 2023
Enter fullscreen mode Exit fullscreen mode

    - The set() method can set specific date and time components such as year, month, day, hour, minute, and second respectively. For example:

calendar.set(2023, 9, 15, 10, 30, 0); // Also set the date to October 15, 2023, 10:30:00
Enter fullscreen mode Exit fullscreen mode
  1. Time Zone Setting     - The setTimeZone() method can be used to set the time zone of the calendar object. For example:
calendar.setTimeZone("Asia/Shanghai"); // Set the time zone of the calendar to the Shanghai time zone
Enter fullscreen mode Exit fullscreen mode

    - Time zone setting is very important for handling time calculation and display across different time zones, ensuring that the application can correctly display the time that conforms to the local time zone in different regions.

  1. Other Property Settings     - Other properties such as the starting day of the week and the minimum number of days in the first week of the year can also be set. For example, the setFirstDayOfWeek() method can be used to set the starting day of the week (such as setting it to Monday: calendar.setFirstDayOfWeek(1)), and the setMinimalDaysInFirstWeek() method can be used to set the minimum number of days in the first week of the year (such as setting it to 3 days: calendar.setMinimalDaysInFirstWeek(3)). These settings can be adjusted according to the habits of different regions and the requirements of the application. ### (III) Using Calendar Objects to Obtain Information
  2. Obtaining Date and Time Information     - Specific date and time values such as year, month, day, hour, minute, and second can be obtained through the calendar object. For example:
let year = calendar.get("year"); // Obtain the year of the current calendar object
let month = calendar.get("month"); // Obtain the month (Note: The month may start counting from 0, depending on the calendar type)
let day = calendar.get("date"); // Obtain the date
let hour = calendar.get("hour"); // Obtain the number of hours
let minute = calendar.get("minute"); // Obtain the number of minutes
let second = calendar.get("second"); // Obtain the number of seconds
Enter fullscreen mode Exit fullscreen mode
  1. Obtaining Time Zone Information     - The getTimeZone() method can be used to obtain the current time zone setting of the calendar object. For example:
let timezone = calendar.getTimeZone(); // Return the time zone string of the current calendar object, such as "Asia/Shanghai"
Enter fullscreen mode Exit fullscreen mode
  1. Obtaining Localized Names and Other Properties     - The localized name of the calendar can be obtained for display to the user in the application. For example:
let calendarName = calendar.getDisplayName("zh - Hans"); // Obtain the localized name of the calendar in the Chinese environment, such as "Gregorian Calendar" or "Chinese Lunar Calendar", etc.
Enter fullscreen mode Exit fullscreen mode

    - Other properties such as the starting day of the week of the calendar object (getFirstDayOfWeek()), the minimum number of days in the first week of the year (getMinimalDaysInFirstWeek()), etc. can also be obtained for relevant logical processing in the application.

III. Handling Time and Dates under Different Calendar Systems

(I) Date Conversion

  1. Conversion between Gregorian Calendar and Chinese Lunar Calendar     - In HarmonyOS applications, the conversion between the Gregorian calendar and the Chinese lunar calendar can be achieved by obtaining the Gregorian calendar and Chinese lunar calendar objects and setting the corresponding dates. For example, to convert a Gregorian date to a Chinese lunar date:
let gregorianCalendar = i18n.getCalendar("zh - Hans", "gregory");
gregorianCalendar.setTime(new Date(2023, 9, 15)); // Set the Gregorian date to October 15, 2023
let lunarCalendar = i18n.getCalendar("zh - Hans", "chinese");
lunarCalendar.setTime(gregorianCalendar.getTimeInMillis()); // Convert the Gregorian date to a Chinese lunar date
let lunarYear = lunarCalendar.get("year"); // Obtain the Chinese lunar year (represented by Heavenly Stems and Earthly Branches)
let lunarMonth = lunarCalendar.get("month"); // Obtain the Chinese lunar month
let lunarDay = lunarCalendar.get("date"); // Obtain the Chinese lunar date
Enter fullscreen mode Exit fullscreen mode

    - Conversely, a Chinese lunar date can also be converted to a Gregorian date by reversing the setting order in the above steps.

  1. Conversion between Other Calendar Systems (if necessary)     - For the conversion between other calendar systems, the principle is similar. First, obtain the calendar objects of the source and target calendar systems, and then convert between the two calendar objects by setting the same time point (using a timestamp or a date object), and obtain the corresponding date and time information. However, it is necessary to pay attention to the characteristics and calculation rules of different calendar systems to ensure the accuracy of the conversion. ### (II) Time Calculation and Comparison
  2. Time Calculation under the Same Calendar System     - Under the same calendar system, the methods of the calendar object can be used for time addition and subtraction calculations. For example, to calculate the date three days after the current date in the Gregorian calendar:
let calendar = i18n.getCalendar("zh - Hans", "gregory");
calendar.setTime(new Date()); // Set to the current date
calendar.add("date", 3); // Add three days to the current date
let newDate = calendar.getTime(); // Obtain the calculated date object
Enter fullscreen mode Exit fullscreen mode

    - Calculations of different time units such as year, month, day, hour, minute, and second can be carried out, and they can be flexibly applied according to the requirements of the application.

  1. Time Comparison under Different Calendar Systems     - When it is necessary to compare times under different calendar systems, they can first be converted to the same calendar system (usually the Gregorian calendar), and then the comparison can be made. For example, to compare the order of a Chinese lunar date and a Gregorian date:
let lunarCalendar = i18n.getCalendar("zh - Hans", "chinese");
lunarCalendar.setTime(new Date(2023, 9, 15)); // Set the Chinese lunar date to September 15, 2023 in the Chinese lunar calendar
let gregorianCalendar = i18n.getCalendar("zh - Hans", "gregory");
gregorianCalendar.setTime(lunarCalendar.getTimeInMillis()); // Convert the Chinese lunar date to a Gregorian date
let anotherGregorianDate = new Date(2023, 10, 1); // Another Gregorian date
if (gregorianCalendar.getTime() < anotherGregorianDate.getTime()) {
    console.log("The Chinese lunar date is before the other Gregorian date");
} else {
    console.log("The Chinese lunar date is after the other Gregorian date");
}
Enter fullscreen mode Exit fullscreen mode

(III) Handling Special Time Points (such as Leap Years, Leap Months)

  1. Leap Year Judgment and Handling     - In the Gregorian calendar, the method of the calendar object can be used to judge leap years. For example:
let calendar = i18n.getCalendar("zh - Hans", "gregory");
calendar.setTime(new Date(2024, 0, 1)); // Set to January 1, 2024
if (calendar.isLeapYear()) {
    console.log("2024 is a leap year");
} else {
    console.log("2024 is not a leap year");
}
Enter fullscreen mode Exit fullscreen mode

    - In the application, for time calculations involving leap years (such as calculating the number of days in a year, the number of days in each month, etc.), special handling according to the leap year rules is required to ensure the accuracy of the calculation results.

  1. Leap Month Handling (Chinese Lunar Calendar)     - For the leap month in the Chinese Lunar Calendar, attention should be paid when obtaining the Chinese lunar date. For example, when obtaining the Chinese lunar month, it is necessary to judge whether it is a leap month and the situation of the leap month. The relevant information about the leap month can be obtained through the methods of the Chinese lunar calendar object, such as judging whether there is a leap month in the current year (hasLeapMonth()), obtaining the month of the leap month (getLeapMonth()), etc. When displaying the Chinese lunar date or performing calculations related to the Chinese lunar month, correct handling according to the leap month situation is required to avoid errors. ## IV. Common Time and Date Handling Problems and Solutions ### (I) Time Zone Related Problems
  2. Problem Description     - When the application runs in different time zones, problems such as incorrect time display and chaotic schedule arrangement times may occur. For example, the schedule reminder set by the user in one time zone may show a time that does not match the expectation when viewed in another time zone; or errors may occur in the transmission and handling of time data in cross-time zone server communication.
  3. Solution     - Always use the correct time zone setting. When obtaining and displaying time, ensure that the time zone setting of the calendar object is consistent with the time zone where the user is located. The time zone of the calendar object can be set by obtaining the system time zone or allowing the user to manually select the time zone. When storing and transmitting time data, it is preferable to use the 0 time zone standard time (UTC or GMT), and convert it according to the user's time zone when displaying it to the user. For example:
let calendar = i18n.getCalendar("zh - Hans", "gregory");
calendar.setTimeZone("Asia/Shanghai"); // Set the time zone of the calendar according to the user's location
let currentTime = calendar.getTime(); // Obtain the time in the current time zone
let utcTime = calendar.getTimeInMillis(); // Obtain the 0 time zone standard time (timestamp) for storage or transmission
// When it is necessary to display the time in other places, convert it according to the user's time zone
let anotherCalendar = i18n.getCalendar("en - US", "gregory");
anotherCalendar.setTimeZone("America/New_York");
anotherCalendar.setTime(utcTime); // Convert the 0 time zone time to the target time zone time and display it
Enter fullscreen mode Exit fullscreen mode

(II) Date Format Display Problems

  1. Solution     - Use the DateTimeFormat class to format the date display. According to the locale identifier of the user's location, select an appropriate date format style (such as setting dateStyle to "full", "long", "medium", "short", etc.) for formatting. For example:
import { intl } from '@kit.LocalizationKit';
let date = new Date(2023, 9, 15);
let dateFormat = new intl.DateTimeFormat("en - GB", {dateStyle: "long"}); // Format the date according to the habits of the British region
let formattedDate = dateFormat.format(date); // Displays as "15 October 2023"
Enter fullscreen mode Exit fullscreen mode

    - The date format can be dynamically adjusted according to the user's language and region settings to provide a good user experience.

(III) Accuracy Problems in Calendar Conversion

  1. Problem Description     - When converting between different calendars, there may be cases where the conversion results are not accurate. For example, after converting a Chinese lunar date to a Gregorian date, there may be a deviation from the actual situation, or errors may occur when dealing with complex calendar rules (such as the special calculation methods of the Islamic calendar).
  2. Solution     - Ensure a thorough understanding of the calculation rules of various calendars and use reliable algorithms for conversion. The calendar handling functions provided by the HarmonyOS system have already undergone certain tests and optimizations. However, in complex situations, developers can refer to relevant calendar standards and algorithm documents for additional verification and optimization. When handling calendar conversion, conduct sufficient testing, including testing of boundary cases (such as extreme dates, special years, etc.), to ensure the accuracy of the conversion results. For example, for the conversion between the Chinese lunar calendar and the Gregorian calendar, comparison tests can be carried out with authoritative Chinese lunar algorithm libraries or online conversion tools to verify the correctness of the conversion results. ### (IV) Boundary Problems in Time Calculation
  3. Problem Description     - When performing time calculations (such as adding or subtracting days, months, etc.), boundary problems may be encountered. For example, the calculation result may exceed the valid range (such as the month exceeding 12 or the date exceeding the maximum number of days in the month), resulting in errors or abnormal behavior of the program.
  4. Solution     - Before performing time calculations, conduct boundary checks and handling. For example, when increasing the month, check whether the calculated month exceeds 12. If it exceeds, perform the corresponding year carry-over processing; when increasing the days, check whether the calculated date exceeds the maximum number of days in the month. If it exceeds, perform month carry-over and date adjustment. The maximum number of days in the month can be obtained using the methods provided by the calendar object (such as the getActualMaximum() method) to assist in boundary handling. For example:
let calendar = i18n.getCalendar("zh - Hans", "gregory");
calendar.setTime(new Date(2023, 11, 31)); // Set to December 31, 2023
calendar.add("month", 1); // Increase by one month
if (calendar.get("month") > 11) {
    calendar.set("year", calendar.get("year") + 1); // Year carry-over
    calendar.set("month", calendar.get("month") - 12); // Adjust the month to the correct range
}
let maxDay = calendar.getActualMaximum("date"); // Get the maximum number of days in the adjusted month
if (calendar.get("date") > maxDay) {
    calendar.set("date", maxDay); // Adjust the date to the maximum number of days in the month
}
Enter fullscreen mode Exit fullscreen mode

(V) Daylight Saving Time Problems (if relevant calendars are involved)

  1. Problem Description     - In some regions that use daylight saving time, the time is adjusted within specific time periods, which may cause errors in the application's handling of time. For example, at the start or end of daylight saving time, the time suddenly jumps. If the application does not handle this correctly, problems such as incorrect schedule reminder times and abnormal time display may occur.
  2. Solution     - The HarmonyOS system will automatically handle the time adjustments related to daylight saving time. Developers need to ensure that when obtaining and displaying time, they are using the time that has been correctly processed by the system. When storing and transmitting time data, the 0 time zone standard time (UTC or GMT) can also be used to avoid the impact of daylight saving time. If the application needs to display on the interface whether it is in daylight saving time, relevant information can be obtained through the calendar object (such as some calendar objects may provide a method to judge whether it is currently in daylight saving time) and inform the user. For example:
let calendar = i18n.getCalendar("zh - Hans", "gregory");
calendar.setTimeZone("Europe/London"); // Set to the London time zone (with daylight saving time)
let isDST = calendar.isDaylightSavingTime(); // Judge whether it is currently in daylight saving time
if (isDST) {
    console.log("Currently in daylight saving time");
} else {
    console.log("Currently not in daylight saving time");
}
Enter fullscreen mode Exit fullscreen mode

(VI) Localized Date and Time Display Problems

  1. Problem Description     - Besides the date format, the localized display of dates and times in different regions may also include other elements, such as the names of weekdays (the representations of Monday to Sunday in different languages), the AM/PM indicators (in the 12-hour clock system), etc. The application may not be able to correctly display these localized elements, or the displayed content may not conform to the local habits.
  2. Solution     - When using the DateTimeFormat class, set relevant parameters to control the display of localized elements. For example, set the weekday parameter to display the correct weekday names (such as "long" for the full name, "short" for the abbreviation), and in the 12-hour clock system, set the hourCycle parameter to display the correct AM/PM indicators (such as "h11" or "h12"). For example:
import { intl } from '@kit.LocalizationKit';
let date = new Date(2023, 9, 15, 14, 30);
let dateFormat = new intl.DateTimeFormat("en - US", {dateStyle: "medium", timeStyle: "medium", weekday: "long", hourCycle: "h12"});
let formattedDate = dateFormat.format(date); // Displays as "Sun, Oct 15, 2023, 2:30 PM" (including the weekday name and the PM indicator)
Enter fullscreen mode Exit fullscreen mode

(VII) Compatibility Problems of Time and Date (with Older Versions or Other Systems)

  1. Problem Description     - When the application needs to interact with older versions of the HarmonyOS system or other operating systems, compatibility problems of time and date formats may be encountered. For example, older versions of the system may use different ways to represent timestamps, or have limited support for date formats.
  2. Solution     - When transmitting and storing data, try to use standardized time formats, such as the timestamp of the 0 time zone standard time (UTC or GMT). When interacting with older versions of the system, perform necessary format conversions and compatibility handling. Special conversion functions can be written to convert the time and date formats according to the characteristics of different systems. For example, convert the specific date format in the older version of the system to a format that can be correctly processed by the HarmonyOS Next system before performing subsequent operations. At the same time, during the update and iteration of the application, consider backward compatibility to ensure that the data of older version users can be used normally after upgrading the system.     Through a deep understanding and effective solution of these common problems, developers can better utilize the calendar and calendar system handling functions of the HarmonyOS Next system to create more stable, accurate, and user-demand-oriented international applications. When handling time and date-related problems, paying attention to details, conducting sufficient testing, and referring to relevant standards and best practices are the keys to ensuring the normal operation of the application on a global scale. It is hoped that this article can provide valuable references and guidance for HarmonyOS system peers in the handling of calendars and calendar systems, helping applications to move forward smoothly on the path of internationalization.
💖 💪 🙅 🚩
xun_wang_6384a403f9817c2
SameX

Posted on November 14, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related