• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2022-2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16import { Log } from './Log';
17import i18n from '@ohos.i18n';
18import Intl from '@ohos.intl';
19
20const TAG: string = 'common_DateUtil';
21
22export class DateUtil {
23  public static readonly MILLISECONDS_PER_SECOND: number = 1000;
24  public static readonly SECONDS_PER_MINUTE: number = 60;
25  public static readonly SECONDS_PER_HOUR: number = 3600;
26  private static LANGUAGE_LOCALES_MAP = {
27    'zh': 'zh-CN',
28    'en': 'en-US'
29  };
30  private static readonly SECONDS_OF_ONE_DAY: number = 24 * 60 * 60;
31
32  // Get the date after localization (year-month-day)
33  public static getLocalizedDate(milliseconds: number): string {
34    let locales: string = this.getLocales();
35    return new Intl.DateTimeFormat(locales, {
36      year: 'numeric',
37      month: 'long',
38      day: 'numeric'
39    }).format(new Date(milliseconds));
40  }
41
42  public static format(time: Date, format_s?: string): string {
43    if (!format_s) {
44      return time.valueOf().toString();
45    }
46    let opts = {
47      'MM': time.getMonth() + 1,
48      'dd': time.getDate(),
49      'HH': time.getHours(),
50      'mm': time.getMinutes(),
51      'ss': time.getSeconds()
52    }
53
54    if (/(y+)/.test(format_s)) {
55      format_s = format_s.replace('yyyy', time.getFullYear().toString().substr(0));
56    }
57    for (let f in opts) {
58      if (new RegExp('(' + f + ')').test(format_s)) {
59        format_s = format_s.replace(f, (f.length == 1) ? opts[f] : (('00' + opts[f]).substr(
60          opts[f].toString().length)))
61      }
62    }
63    return format_s;
64  }
65
66  public static getDateTimeFormat(milliseconds: number): string {
67    return DateUtil.format(new Date(milliseconds), 'yyyy/MM/dd HH:mm:ss');
68  }
69
70  // Gets the localization date of the photo page grouping data
71  public static getGroupDataLocalizedDate(milliseconds: number): Resource {
72    let date = new Date(milliseconds);
73    let today = new Date();
74    if (date.getFullYear() == today.getFullYear() && date.getMonth() == today.getMonth()) {
75      if (date.getDate() == today.getDate()) {
76        return $r('app.string.date_today');
77      }
78      if (today.getDate() - date.getDate() == 1) {
79        return $r('app.string.date_yesterday');
80      }
81    }
82    return $r('app.string.common_place_holder', this.getLocalizedDate(milliseconds));
83  }
84
85  public static getLocalizedYear(milliseconds: number): Resource {
86    let locales: string = this.getLocales();
87    let yearText = new Intl.DateTimeFormat(locales, {
88      year: 'numeric'
89    }).format(new Date(milliseconds));
90    return $r('app.string.common_place_holder', yearText.toString());
91  }
92
93  public static getLocalizedYearAndMonth(milliseconds: number): string {
94    let locales: string = this.getLocales();
95    return new Intl.DateTimeFormat(locales, {
96      year: 'numeric',
97      month: 'long'
98    }).format(new Date(milliseconds));
99  }
100
101  public static getLocalizedTime(milliseconds: number): string {
102    let locales: string = this.getLocales();
103    let is24HourClock = i18n.is24HourClock();
104    Log.info(TAG, `get is24HourClock ${is24HourClock}`);
105    return new Intl.DateTimeFormat(locales, {
106      hour: (!is24HourClock ? '2-digit' : 'numeric'),
107      minute: '2-digit'
108    }).format(new Date(milliseconds));
109  }
110
111  // Format duration
112  public static getFormattedDuration(milliSecond: number): string {
113    if (milliSecond == null) {
114      Log.error(TAG, 'getFormattedDuration, input is null!');
115      return '00:00';
116    }
117    if (milliSecond <= 0) {
118      Log.error(TAG, 'getFormattedDuration, input is negative number!');
119      return '00:00';
120    }
121    if (milliSecond < this.MILLISECONDS_PER_SECOND) {
122      return '00:01';
123    }
124    let seconds = Math.floor(milliSecond / this.MILLISECONDS_PER_SECOND);
125    let hourTime: number = Math.floor(seconds / this.SECONDS_PER_HOUR);
126    let minuteTime: number = Math.floor(Math.floor(seconds / this.SECONDS_PER_MINUTE) % this.SECONDS_PER_MINUTE);
127    let secondTime: number = Math.floor(seconds % this.SECONDS_PER_MINUTE);
128    if (hourTime > 0) {
129      return `${hourTime}:${this.checkTime(minuteTime)}:${this.checkTime(secondTime)}`;
130    } else {
131      return `${this.checkTime(minuteTime)}:${this.checkTime(secondTime)}`;
132    }
133  }
134
135  public static isTheSameDay(startTime: number, endTime: number): boolean {
136    if (startTime == null || endTime == null) {
137      return false;
138    }
139    const startTimeMs = new Date(startTime).setHours(0, 0, 0, 0);
140    const endTimeMs = new Date(endTime).setHours(0, 0, 0, 0);
141    return startTimeMs === endTimeMs ? true : false;
142  }
143
144  public static isTheSameYear(startTime: number, endTime: number): boolean {
145    if (startTime == null || endTime == null) {
146      return false;
147    }
148    const startYear = new Date(startTime).getFullYear();
149    const endYear = new Date(endTime).getFullYear();
150    return startYear === endYear ? true : false;
151  }
152
153  // Seconds converted to days (Less than 1 day is counted as 1 day)
154  public static convertSecondsToDays(seconds: number): number {
155    if (seconds % this.SECONDS_OF_ONE_DAY == 0) {
156      return seconds / this.SECONDS_OF_ONE_DAY;
157    } else {
158      return parseInt(seconds / this.SECONDS_OF_ONE_DAY + '') + 1;
159    }
160  }
161
162  public static isEmpty(obj: unknown): boolean {
163    return obj == undefined || obj == null;
164  }
165
166  private static getLocales(): string {
167    let systemLocale = i18n.getSystemLanguage();
168    let language = systemLocale.split('-')[0];
169    let locales: string = this.LANGUAGE_LOCALES_MAP['en'];
170    if (this.LANGUAGE_LOCALES_MAP[language]) {
171      locales = this.LANGUAGE_LOCALES_MAP[language];
172    }
173    return locales;
174  }
175
176  private static checkTime(time: number): string {
177    if (time < 0) {
178      Log.error(TAG, 'checkTime, input is negative number!');
179      return '00';
180    }
181    let formatTime: string = time.toString();
182    if (time < 10) {
183      let zeroString = '0';
184      formatTime = zeroString.concat(formatTime);
185    }
186    return formatTime;
187  }
188}