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