鸿蒙应用示例:工作中常用的日期时间处理方法

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

@Entry
@Component
struct Index {
  @State formattedTimeNow: string = "";
  @State formattedTimeAgo: string = "";
  @State timestampSecs: string = "";
  @State timestampSecsAlt: string = "";
  @State fullDateTime: string = "";
  @State nanosecondsTimestamp: string = "";
  @State timezoneOffsetHours: string = "";
  @State currentDate: string = "";
  @State formattedSpecifiedDateTime: string = "";

  formatTimeAgo(dateTime: Date): string {
    const now = new Date();
    const diff = now.getTime() - dateTime.getTime();
    const SECONDS = 1000;
    const MINUTES = SECONDS * 60;
    const HOURS = MINUTES * 60;
    const DAYS = HOURS * 24;

    if (diff < SECONDS) {
      return '刚刚';
    } else if (diff < MINUTES) {
      return '不到一分钟';
    } else if (diff < HOURS) {
      return Math.round(diff / MINUTES) + '分钟前';
    } else if (diff < DAYS) {
      return Math.round(diff / HOURS) + '小时前';
    } else if (diff < DAYS * 2) {
      return '昨天';
    } else if (diff < DAYS * 3) {
      return '前天';
    } else {
      return this.formatDate(dateTime);
    }
  }

  formatDate(dateTime: Date): string {
    const year = dateTime.getFullYear();
    const month = String(dateTime.getMonth() + 1).padStart(2, '0');
    const day = String(dateTime.getDate()).padStart(2, '0');
    return `${year}年${month}月${day}日`;
  }

  getFullDateTime(): string {
    const formatter = new Intl.DateTimeFormat('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
    return formatter.format(new Date());
  }

  formatCustomDateTime(dateTime: Date): string {
    const formatter = new Intl.DateTimeFormat('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    });
    const parts = formatter.formatToParts(dateTime);
    let formattedDate = '';
    for (const part of parts) {
      switch (part.type) {
        case 'month':
          formattedDate += `${part.value}月`;
          break;
        case 'day':
          formattedDate += `${part.value}日`;
          break;
        case 'year':
          formattedDate = `${part.value}年${formattedDate}`;
          break;
        default:
          break;
      }
    }
    return formattedDate;
  }

  getFormattedSpecifiedDateTime(dateTime: Date): string {
    return this.formatCustomDateTime(dateTime);
  }

  getNanosecondsTimestamp(): void {
    const time = systemDateTime.getTime(true);
    this.nanosecondsTimestamp = time.toString();
  }

  getTimezoneOffsetHours(): void {
    try {
      const now = new Date();
      const offsetMinutes = now.getTimezoneOffset();
      const offsetHours = Math.floor(-offsetMinutes / 60);
      this.timezoneOffsetHours = offsetHours.toString();
    } catch (error) {
      console.error('获取时区偏移量失败:', error);
      this.timezoneOffsetHours = '未知';
    }
  }

  getCurrentYearMonthDay(): string {
    const date = new Date();
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}年${month}月${day}日`;
  }

  build() {
    Column({ space: 10 }) {
      Button('获取当前时间戳(秒)').onClick(() => {
        this.timestampSecs = Math.floor(Date.now() / 1000).toString()
        this.timestampSecsAlt = Math.floor(new Date().getTime() / 1000).toString()
      })
      Text(`当前时间戳(秒):${this.timestampSecs}`)
      Text(`当前时间戳(秒):${this.timestampSecsAlt}`)

      Button('获取当前时间戳(纳秒)').onClick(() => {
        this.getNanosecondsTimestamp();
      })
      Text(`当前时间戳(纳秒):${this.nanosecondsTimestamp}`)

      Button('获取时间间隔显示').onClick(() => {
        this.formattedTimeNow = this.formatTimeAgo(new Date());
        this.formattedTimeAgo = this.formatTimeAgo(new Date('2023-04-01T12:00:00'));
      })
      Text(`当前时间间隔显示:${this.formattedTimeNow}`)
      Text(`指定时间间隔显示:${this.formattedTimeAgo}`)

      Button('获取当前时区偏移量').onClick(() => {
        this.getTimezoneOffsetHours();
      })

      Text(`当前时区偏移量:${this.timezoneOffsetHours}小时`)

      Button('获取当前年-月-日').onClick(() => {
        this.currentDate = this.getCurrentYearMonthDay();
      })
      Text(`当前年-月-日:${this.currentDate}`)

      Button('获取当前完整时间').onClick(() => {
        this.fullDateTime = this.getFullDateTime();
      })
      Text(`当前完整时间:${this.fullDateTime}`)

      Button('获取指定日期时间').onClick(() => {
        this.formattedSpecifiedDateTime = this.getFormattedSpecifiedDateTime(new Date('2024-10-02T09:30:00'));
      })
      Text(`指定日期时间:${this.formattedSpecifiedDateTime}`)
    }
    .width('100%')
    .height('100%')
  }
}

实现了以下功能:

1. 获取当前时间戳(秒级和纳秒级)。
2. 格式化时间差,显示为“刚刚”、“几分钟前”等形式。
3. 获取当前时间的完整格式(年-月-日 时:分:秒)。
4. 获取指定日期的时间格式。
5. 获取当前时区偏移量。
6. 获取当前日期(年-月-日)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值