实现了以下功能:

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

代码解析

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}日`;
  }

  // UI布局
  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%')
  }
}

zhongcx
1 声望3 粉丝