1/* 2 * Copyright (c) 2024 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 date 日期对象 19 * @param format 日期格式,默认为 YYYY-MM-DD HH:mm:ss 20 */ 21export const formatDate = (date: Date, format = 'YYYY-MM-DD HH:mm:ss') => { 22 // 获取年月日时分秒,通过 padStart 补 0 23 const year = String(date.getFullYear()) 24 const month = String(date.getMonth() + 1).padStart(2, '0') 25 const day = String(date.getDate()).padStart(2, '0') 26 const hours = String(date.getHours()).padStart(2, '0') 27 const minutes = String(date.getMinutes()).padStart(2, '0') 28 const seconds = String(date.getSeconds()).padStart(2, '0') 29 30 // 返回格式化后的结果 31 return format 32 .replace('YYYY', year) 33 .replace('MM', month) 34 .replace('DD', day) 35 .replace('HH', hours) 36 .replace('mm', minutes) 37 .replace('ss', seconds) 38}