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

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
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%')
  }
}

  

 

posted @   zhongcx  阅读(66)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示