写点什么

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

作者:zhongcx
  • 2024-10-12
    广东
  • 本文字数:2549 字

    阅读完需:约 8 分钟


import { systemDateTime } from '@kit.BasicServicesKit';
@Entry@Componentstruct 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. 获取当前日期(年-月-日)。

用户头像

zhongcx

关注

还未添加个人签名 2024-09-27 加入

还未添加个人简介

评论

发布
暂无评论
鸿蒙应用示例:工作中常用的日期时间处理方法_zhongcx_InfoQ写作社区