HarmonyOS NEXT 不同日期的天数差值方案分享

2025-03-19 20:56:10
139次阅读
0个评论

【功能概述】

这是一个基于ArkUI框架开发的鸿蒙应用组件,用于计算不同日期之间的天数差(如高考倒计时场景)。通过双日期选择器(DatePicker)实现用户输入,动态展示日期差异结果,适用于倒计时、日程管理等场景。

【实现效果】

GIF 2025-3-17 20-09-59.gif

【环境准备】

• 操作系统:Windows 10 • 开发工具:DevEco Studio(5.0.7.210) • 目标设备:华为Mate60 Pro • 开发语言:ArkTS • 框架:ArkUI • API版本:API 14

【工程目录】

│  ├─ hvigorfile.ts
│  ├─ obfuscation-rules.txt
│  ├─ oh-package.json5                           //声明依赖
│  └─ src
│     ├─ main
│     │  ├─ ets
│     │  │  ├─ entryability
│     │  │  │  └─ EntryAbility.ets               //程序入口类
│     │  │  ├─ entrybackupability
│     │  │  │  └─ EntryBackupAbility.ets
│     │  │  └─ pages
│     │  │     └─ Index.ets                      //主页入口
│     │  ├─ module.json5                         //相关模块配置
│     │  └─ resources                            //应用静态资源
│     │     ├─ base
│     │     │  ├─ element
│     │     │  │  ├─ color.json
│     │     │  │  ├─ float.json
│     │     │  │  └─ string.json
│     │     │  ├─ media
│     │     │  │  ├─ background.png
│     │     │  │  ├─ foreground.png
│     │     │  │  ├─ layered_image.json
│     │     │  │  └─ startIcon.png
│     │     │  └─ profile
│     │     │     ├─ backup_config.json
│     │     │     └─ main_pages.json
│     │     ├─ dark
│     │     │  └─ element
│     │     │     └─ color.json
│     │     └─ rawfile

【核心功能】

  1. 双日期选择 ○ 提供两个日期选择器,用户可自由设定起始日期(日期一)与目标日期(日期二)。 ○ 日期范围覆盖1900年至2100年,满足长期跨度的计算需求。

  2. 动态时间差计算 ○ 实时计算两日期的时间差,结果以天数形式展示。 ○ 支持正负值反馈:日期二晚于日期一时显示正数,反之显示负数。

  3. 自适应界面 ○ 使用响应式布局(Row/Column),适配不同屏幕尺寸。 ○ 通过@State实现数据与视图的动态绑定,确保界面实时更新。

【具体实现】

  1. 状态管理 ● @State daysToCollegeEntranceExamination:存储两日期的天数差,通过装饰器实现状态驱动UI更新。 ● Date1与Date2:分别记录用户选择的两个日期。

  2. 计算逻辑

  let data1 = new Date(this.Date1);  
  let data2 = new Date(this.Date2);  
  let timeDiff1 = Math.abs(data1.getTime());  
  let timeDiff2 = Math.abs(data2.getTime());  
  let timeDiff3 = timeDiff2 - timeDiff1;  
  this.daysToCollegeEntranceExamination = Math.ceil(timeDiff3 / (1000 * 3600 * 24));  
  return timeDiff1 < timeDiff2 ? this.daysToCollegeEntranceExamination : -1 * this.daysToCollegeEntranceExamination;  
}

● 关键点:通过时间戳差值计算天数差,Math.ceil确保向上取整,避免零头天数遗漏。 ● 正负判断:根据两日期的先后关系返回正负值,直观反馈时间方向性。

  1. 界面设计
  Column() {  
    // 日期选择器模块  
    DatePicker({...})  
      .backgroundColor('#ededed')  
      .selectedTextStyle({ color: '#ee8848' })  
      .onDateChange((value: Date) => {  
        this.Date1 = value;  
        this.X1();  
      });  
    // 结果展示  
    Text(`${this.daysToCollegeEntranceExamination}天`)  
      .fontSize(45)  
      .fontWeight(FontWeight.Bold);  
  }  
}

● 视觉设计:灰底圆角日期选择器(borderRadius:30),高亮选中日期(#ee8848)。 ● 交互响应:日期变更时触发onDateChange事件,实时更新计算结果。

【完整代码】

@Component
export default struct  TimeDifference{

  @State daysToCollegeEntranceExamination: number = 0 //距离高考时间
  private Date2: Date = new Date() // 日期2
  private Date1: Date = new Date() // 日期1

  private X1(): number {
    let data1 = new Date(this.Date1); // 将选中的第一个日期字符串转换为Date对象
    let data2 = new Date(this.Date2); // 将选中的第二个日期字符串转换为Date对象
    let timeDiff1 = Math.abs(data1.getTime()); // 设定时间
    let timeDiff2 = Math.abs(data2.getTime()); // 高考时间
    let timeDiff3 = timeDiff2-timeDiff1
    this.daysToCollegeEntranceExamination = Math.ceil(timeDiff3 / (1000 * 3600 * 24)); // 转换为天数
    if (timeDiff1<timeDiff2) {
      return this.daysToCollegeEntranceExamination
    }
    return -1*this.daysToCollegeEntranceExamination
  }

  build(){
      Column() {
        Column({ space: 3 }) {
          Row() {
            Column() {
              Text('【日期一】')
                .fontColor(Color.Black)
                .fontSize(30)
                  //.backgroundColor('#82c67b')
                .width(200)
                .textAlign(TextAlign.Center)
                .margin({top:0,bottom:5})
                .borderRadius(5)
              DatePicker({
                // 创建日期选择器
                start: new Date('1900-1-1'), // 设置起始日期
                end: new Date('2100-1-1'), // 设置结束日期
                selected: this.Date1 // 设置日期1,默认当前日期
              })
                .borderRadius(30)
                .backgroundColor('#ededed')
                .width('95%')
                .margin({ bottom: 6 })
                .height('400lpx')// 设置高度
                .disappearTextStyle({ color: Color.Gray, font: { size: '13fp', weight: FontWeight.Bold } })// 设置消失文本样式
                .textStyle({ color: Color.Black, font: { size: '13fp', weight: FontWeight.Normal } })// 设置文本样式
                .selectedTextStyle({
                  color:'#ee8848',
                  font: { size: '16fp', weight: FontWeight.Regular }
                })// 设置选定文本样式
                .onDateChange((value: Date) => { // 日期选择器变化时的处理
                  this.Date1 = value; // 设置选定的日期
                  this.X1()
                })
            }
            .margin({top:13})
          }

          Row() {
            Column() {
              Text('【日期二】')
                .fontColor(Color.Black)
                .fontSize(30)
                  //.backgroundColor('#82c67b')
                .width(200)
                .textAlign(TextAlign.Center)
                .margin({ top:10,bottom:5 })
                .borderRadius(5)
              DatePicker({
                // 创建日期选择器
                start: new Date('1900-1-1'), // 设置起始日期
                end: new Date('2100-1-1'), // 设置结束日期
                selected: this.Date2 // 设置日期2,默认当前日期
              })
                .backgroundColor('#ededed')
                .borderRadius(30)
                .width('95%')
                .margin({ bottom: 6 })
                .height('400lpx')// 设置高度
                .disappearTextStyle({ color: Color.Gray, font: { size: '13fp', weight: FontWeight.Bold } })// 设置消失文本样式
                .textStyle({ color: Color.Black, font: { size: '13fp', weight: FontWeight.Normal } })// 设置文本样式
                .selectedTextStyle({
                  color: '#ee8848',
                  font: { size: '16fp', weight: FontWeight.Regular }
                })// 设置选定文本样式
                .onDateChange((value: Date) => { // 日期选择器变化时的处理
                  this.Date2 = value; // 设置高考日期
                  this.X1()
                })
            }
          }
        }
        Text(`${this.daysToCollegeEntranceExamination}天`)
          .fontColor(Color.Black)
          .margin({ top:14})
          .fontSize(45)
          .fontWeight(FontWeight.Bold)
      }
      .height('100%')
      .width('100%')
      .backgroundColor(Color.White)
  }
}

收藏00

登录 后评论。没有帐号? 注册 一个。