• 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
16/**
17 * 日期格式化
18 * @param Number time 时间戳
19 * @param String format 格式
20 */
21export function dateFormat(time?: number, format: string='Y-m-d h:i:s') {
22    const t = new Date(time)
23    // 日期格式
24    format = format || 'Y-m-d h:i:s'
25    let year = t.getFullYear()
26    // 由于 getMonth 返回值会比正常月份小 1
27    let month = t.getMonth() + 1
28    let day = t.getDate()
29    let hours = t.getHours()
30    let minutes = t.getMinutes()
31    let seconds = t.getSeconds()
32
33    const hash = {
34        'y': year,
35        'm': month,
36        'd': day,
37        'h': hours,
38        'i': minutes,
39        's': seconds
40    }
41    // 是否补 0
42    const isAddZero = (o) => {
43        return /m|d|h|i|s/.test(o)
44    }
45    return format.replace(/\w/g, o => {
46        let rt = hash[o.toLocaleLowerCase()]
47        return rt > 9 || !isAddZero(o) ? rt : `0${rt}`
48    })
49}
50/**
51 * 计时器 转 时分秒字符串 HH:mm:ss
52 * @param time
53 */
54export function secToTime(time: number): String {
55    var timeStr: String = null
56    var hour: number = 0
57    var minute: number = 0
58    var second: number = 0
59    if (time <= 0) {
60        return "00:00"
61    } else {
62        minute = parseInt((time / 60).toString())
63        if (minute < 60) {
64            second = time % 60
65            timeStr = unitFormat(minute) + ":" + unitFormat(second)
66        } else {
67            hour = parseInt((minute / 60).toString())
68            minute = minute % 60
69            second = time - hour * 3600 - minute * 60
70            timeStr =
71            unitFormat(hour) + ":" + unitFormat(minute) + ":" + unitFormat(second)
72        }
73    }
74    return timeStr
75}
76
77export function unitFormat(i: number): String {
78    var retStr: String
79    if (i >= 0 && i < 10) {
80        retStr = "0" + i.toString()
81    } else {
82        retStr = "" + i.toString()
83    }
84    return retStr
85}