HarmonyOS NEXT Development Case: Age Calculator

This article demonstrates an age calculation implementation in HarmonyOS NEXT, featuring comprehensive date information display including Gregorian/Lunar calendar conversions, zodiac signs, and astronomical statistics. Key Features Dual calendar system support (Gregorian & Lunar) Age calculation (Real age & Nominal age) Zodiac and Chinese zodiac display Next birthday countdown Life duration statistics (months/days/hours) Seasonal determination Festival recognition Implementation Overview 1. Core Data Structure class Info { sYear: number = 0 // Gregorian year sMonth: number = 0 // Gregorian month sDay: number = 0 // Gregorian day week: number = 0 // Weekday index (0-6) weekZH: string = "" // Weekday in Chinese date: string = "" // Formatted date string zodiac: string = "" // Western zodiac sign lYear: number = 0 // Lunar year lMonth: number = 0 // Lunar month lDay: number = 0 // Lunar day isLeap: boolean = false // Leap month flag lMonthZH: string = "" // Lunar month in Chinese lDayZH: string = "" // Lunar day in Chinese gzYearZH: string = "" // Heavenly stem/Earthly branch year gzMonthZH: string = "" // Heavenly stem/Earthly branch month gzDayZH: string = "" // Heavenly stem/Earthly branch day animal: string = "" // Chinese zodiac animal term: string = "" // Solar term festival: string = "" // Festival information } 2. State Management @Entry @Component struct AgeCalculatorPage { @State season: string = '-' @State realAge: number = 0 @State lunarAge: number = 0 @State festival: string = '-' @State weekday: string = '-' @State isLunar: boolean = false @State zodiac: string = '-' @State animal: string = '-' @State daysToNextGregorianBirthday: number = 0 @State daysToNextLunarBirthday: number = 0 @State dayOfWeekNextGregorianBirthday: number = 0 @State dayOfWeekNextLunarBirthday: number = 0 @State totalMonthsAlive: number = 0 @State totalDaysAlive: number = 0 @State totalHoursAlive: number = 0 @State gregorianBirthDate: string = '-' @State lunarBirthDate: string = '-' private selectedBirthDate: Date = new Date('1989-01-17') private weekdays: string[] = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] } 3. Core Algorithms Age Calculation private calculateRealAge(birthInfo: Info) { const today = new Date() let realAge = today.getFullYear() - birthInfo.sYear if (today.getMonth() { // Handle date change events }) } } Technical Highlights Dual Calendar Integration Utilizes calendar-tool library for lunar date conversions Supports bidirectional conversion between Gregorian and Lunar dates Reactive UI Uses @State decorators for automatic UI updates Implements complex layout with Scroll/Row/Column components Performance Optimization Memoization of date calculations Efficient date difference algorithms Localization Support Chinese cultural elements (Zodiac, Stems-Branches) Localized date formatting Conclusion This implementation demonstrates HarmonyOS NEXT's capabilities in handling complex date calculations and cultural-specific requirements. The component-based architecture and reactive programming model enable efficient development of feature-rich applications.

May 11, 2025 - 04:26
 0
HarmonyOS NEXT Development Case: Age Calculator

Image description

This article demonstrates an age calculation implementation in HarmonyOS NEXT, featuring comprehensive date information display including Gregorian/Lunar calendar conversions, zodiac signs, and astronomical statistics.

Key Features

  • Dual calendar system support (Gregorian & Lunar)
  • Age calculation (Real age & Nominal age)
  • Zodiac and Chinese zodiac display
  • Next birthday countdown
  • Life duration statistics (months/days/hours)
  • Seasonal determination
  • Festival recognition

Implementation Overview

1. Core Data Structure

class Info {
  sYear: number = 0       // Gregorian year
  sMonth: number = 0      // Gregorian month
  sDay: number = 0        // Gregorian day
  week: number = 0        // Weekday index (0-6)
  weekZH: string = ""     // Weekday in Chinese
  date: string = ""       // Formatted date string
  zodiac: string = ""     // Western zodiac sign
  lYear: number = 0       // Lunar year
  lMonth: number = 0      // Lunar month
  lDay: number = 0        // Lunar day
  isLeap: boolean = false // Leap month flag
  lMonthZH: string = ""   // Lunar month in Chinese
  lDayZH: string = ""     // Lunar day in Chinese
  gzYearZH: string = ""   // Heavenly stem/Earthly branch year
  gzMonthZH: string = ""  // Heavenly stem/Earthly branch month
  gzDayZH: string = ""    // Heavenly stem/Earthly branch day
  animal: string = ""     // Chinese zodiac animal
  term: string = ""       // Solar term
  festival: string = ""   // Festival information
}

2. State Management

@Entry
@Component
struct AgeCalculatorPage {
  @State season: string = '-'
  @State realAge: number = 0
  @State lunarAge: number = 0
  @State festival: string = '-'
  @State weekday: string = '-'
  @State isLunar: boolean = false
  @State zodiac: string = '-'
  @State animal: string = '-'
  @State daysToNextGregorianBirthday: number = 0
  @State daysToNextLunarBirthday: number = 0
  @State dayOfWeekNextGregorianBirthday: number = 0
  @State dayOfWeekNextLunarBirthday: number = 0
  @State totalMonthsAlive: number = 0
  @State totalDaysAlive: number = 0
  @State totalHoursAlive: number = 0
  @State gregorianBirthDate: string = '-'
  @State lunarBirthDate: string = '-'

  private selectedBirthDate: Date = new Date('1989-01-17')
  private weekdays: string[] = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 
                               'Thursday', 'Friday', 'Saturday']
}

3. Core Algorithms

Age Calculation

private calculateRealAge(birthInfo: Info) {
  const today = new Date()
  let realAge = today.getFullYear() - birthInfo.sYear

  if (today.getMonth() < birthInfo.sMonth - 1 || 
      (today.getMonth() === birthInfo.sMonth - 1 && 
       today.getDate() < birthInfo.sDay)) {
    realAge--
  }
  this.realAge = realAge
}

Lunar Age Calculation

private calculateLunarAge() {
  const today = new Date()
  const lunarNewYear = new Date(today.getFullYear(), 1, 22)
  let lunarAge = this.realAge + 1

  if (today < lunarNewYear) {
    lunarAge--
  }
  this.lunarAge = lunarAge
}

Life Duration Calculation

private calculateEarthTime(birthDate: Date) {
  const currentDate = new Date()
  const diff = currentDate.getTime() - birthDate.getTime()

  this.totalMonthsAlive = Math.floor(diff / (1000 * 60 * 60 * 24 * 30.44))
  this.totalDaysAlive = Math.floor(diff / (1000 * 60 * 60 * 24))
  this.totalHoursAlive = Math.floor(diff / (1000 * 60 * 60))
}

4. UI Components

build() {
  Column() {
    Text("Age Calculator")
      .width('100%')
      .height(44)
      .backgroundColor(Color.Orange)
      .textAlign(TextAlign.Center)
      .fontColor(Color.White)

    Scroll() {
      // UI layout implementation
      // Contains multiple Row/Column components for data display
      // Uses border styling and flexible layout
    }

    DatePicker({
      start: new Date('1900-1-1'),
      end: new Date('2100-1-1'),
      selected: this.selectedBirthDate
    })
    .onDateChange((value: Date) => {
      // Handle date change events
    })
  }
}

Technical Highlights

  1. Dual Calendar Integration

    • Utilizes calendar-tool library for lunar date conversions
    • Supports bidirectional conversion between Gregorian and Lunar dates
  2. Reactive UI

    • Uses @State decorators for automatic UI updates
    • Implements complex layout with Scroll/Row/Column components
  3. Performance Optimization

    • Memoization of date calculations
    • Efficient date difference algorithms
  4. Localization Support

    • Chinese cultural elements (Zodiac, Stems-Branches)
    • Localized date formatting

Conclusion

This implementation demonstrates HarmonyOS NEXT's capabilities in handling complex date calculations and cultural-specific requirements. The component-based architecture and reactive programming model enable efficient development of feature-rich applications.