• 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    if(milliseconds === undefined){
35      milliseconds = new Date().getTime()
36    }
37    let locales: string = this.getLocales();
38    return new Intl.DateTimeFormat(locales, {
39      year: 'numeric',
40      month: 'long',
41      day: 'numeric'
42    }).format(new Date(milliseconds));
43  }
44
45  public static format(time: Date, format_s?: string): string {
46    if (!format_s) {
47      return time.valueOf().toString();
48    }
49    let opts = {
50      'MM': time.getMonth() + 1,
51      'dd': time.getDate(),
52      'HH': time.getHours(),
53      'mm': time.getMinutes(),
54      'ss': time.getSeconds()
55    }
56
57    if (/(y+)/.test(format_s)) {
58      format_s = format_s.replace('yyyy', time.getFullYear().toString().substr(0));
59    }
60    for (let f in opts) {
61      if (new RegExp('(' + f + ')').test(format_s)) {
62        format_s = format_s.replace(f, (f.length == 1) ? opts[f] : (('00' + opts[f]).substr(
63          opts[f].toString().length)))
64      }
65    }
66    return format_s;
67  }
68
69  public static getDateTimeFormat(milliseconds: number): string {
70    return DateUtil.format(new Date(milliseconds), 'yyyy/MM/dd HH:mm:ss');
71  }
72
73  // Gets the localization date of the photo page grouping data
74  public static getGroupDataLocalizedDate(milliseconds: number): Resource {
75    let date = new Date(milliseconds);
76    let today = new Date();
77    if (date.getFullYear() == today.getFullYear() && date.getMonth() == today.getMonth()) {
78      if (date.getDate() == today.getDate()) {
79        return $r('app.string.date_today');
80      }
81      if (today.getDate() - date.getDate() == 1) {
82        return $r('app.string.date_yesterday');
83      }
84    }
85    return $r('app.string.common_place_holder', this.getLocalizedDate(milliseconds));
86  }
87
88  public static getLocalizedYear(milliseconds: number): Resource {
89    let locales: string = this.getLocales();
90    let yearText = new Intl.DateTimeFormat(locales, {
91      year: 'numeric'
92    }).format(new Date(milliseconds));
93    return $r('app.string.common_place_holder', yearText.toString());
94  }
95
96  public static getLocalizedYearAndMonth(milliseconds: number): string {
97    let locales: string = this.getLocales();
98    return new Intl.DateTimeFormat(locales, {
99      year: 'numeric',
100      month: 'long'
101    }).format(new Date(milliseconds));
102  }
103
104  public static getLocalizedTime(milliseconds: number): string {
105    let locales: string = this.getLocales();
106    let is24HourClock = i18n.is24HourClock();
107    Log.info(TAG, `get is24HourClock ${is24HourClock}`);
108    return new Intl.DateTimeFormat(locales, {
109      hour: (!is24HourClock ? '2-digit' : 'numeric'),
110      minute: '2-digit'
111    }).format(new Date(milliseconds));
112  }
113
114  // Format duration
115  public static getFormattedDuration(milliSecond: number): string {
116    if (milliSecond == null) {
117      Log.error(TAG, 'getFormattedDuration, input is null!');
118      return '00:00';
119    }
120    if (milliSecond <= 0) {
121      Log.error(TAG, 'getFormattedDuration, input is negative number!');
122      return '00:00';
123    }
124    if (milliSecond < this.MILLISECONDS_PER_SECOND) {
125      return '00:01';
126    }
127    let seconds = Math.floor(milliSecond / this.MILLISECONDS_PER_SECOND);
128    let hourTime: number = Math.floor(seconds / this.SECONDS_PER_HOUR);
129    let minuteTime: number = Math.floor(Math.floor(seconds / this.SECONDS_PER_MINUTE) % this.SECONDS_PER_MINUTE);
130    let secondTime: number = Math.floor(seconds % this.SECONDS_PER_MINUTE);
131    if (hourTime > 0) {
132      return `${hourTime}:${this.checkTime(minuteTime)}:${this.checkTime(secondTime)}`;
133    } else {
134      return `${this.checkTime(minuteTime)}:${this.checkTime(secondTime)}`;
135    }
136  }
137
138  public static isTheSameDay(startTime: number, endTime: number): boolean {
139    if (startTime == null || endTime == null) {
140      return false;
141    }
142    const startTimeMs = new Date(startTime).setHours(0, 0, 0, 0);
143    const endTimeMs = new Date(endTime).setHours(0, 0, 0, 0);
144    return startTimeMs === endTimeMs ? true : false;
145  }
146
147  public static isTheSameYear(startTime: number, endTime: number): boolean {
148    if (startTime == null || endTime == null) {
149      return false;
150    }
151    const startYear = new Date(startTime).getFullYear();
152    const endYear = new Date(endTime).getFullYear();
153    return startYear === endYear ? true : false;
154  }
155
156  // Seconds converted to days (Less than 1 day is counted as 1 day)
157  public static convertSecondsToDays(seconds: number): number {
158    if (seconds % this.SECONDS_OF_ONE_DAY == 0) {
159      return seconds / this.SECONDS_OF_ONE_DAY;
160    } else {
161      return parseInt(seconds / this.SECONDS_OF_ONE_DAY + '') + 1;
162    }
163  }
164
165  public static isEmpty(obj: unknown): boolean {
166    return obj == undefined || obj == null;
167  }
168
169  private static getLocales(): string {
170    let systemLocale = i18n.getSystemLanguage();
171    let language = systemLocale.split('-')[0];
172    let locales: string = this.LANGUAGE_LOCALES_MAP['en'];
173    if (this.LANGUAGE_LOCALES_MAP[language]) {
174      locales = this.LANGUAGE_LOCALES_MAP[language];
175    }
176    return locales;
177  }
178
179  private static checkTime(time: number): string {
180    if (time < 0) {
181      Log.error(TAG, 'checkTime, input is negative number!');
182      return '00';
183    }
184    let formatTime: string = time.toString();
185    if (time < 10) {
186      let zeroString = '0';
187      formatTime = zeroString.concat(formatTime);
188    }
189    return formatTime;
190  }
191}