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 16export class DateUtil { 17 private static readonly NEW_NAME_IMG: string = 'IMG_'; 18 private static readonly NEW_NAME_EDIT: string = 'edit_'; 19 20 public static formats(format?: string): string { 21 let time = new Date(); 22 if (!format) { 23 return time.valueOf().toString(); 24 } 25 let opts = { 26 'MM': time.getMonth() + 1, 27 'dd': time.getDate(), 28 'HH': time.getHours(), 29 'mm': time.getMinutes(), 30 'ss': time.getSeconds() 31 }; 32 33 if (/(y+)/.test(format)) { 34 format = format.replace('yyyy', time.getFullYear().toString().substr(0)); 35 } 36 for (let f in opts) { 37 if (new RegExp('(' + f + ')').test(format)) { 38 format = format.replace(f, (f.length == 1) ? opts[f] : (('00' + opts[f]).substr( 39 opts[f].toString().length))); 40 } 41 } 42 return format; 43 } 44 45 public static nameByDate(isReplace: Boolean, name?: string): string { 46 if (isReplace) { 47 return (!name) ? null : (name.indexOf(`${DateUtil.NEW_NAME_EDIT}`) == -1 ? name.split('.')[0] + '_' + DateUtil.NEW_NAME_EDIT + DateUtil.formats() : name.split('.')[0]); 48 } else { 49 return DateUtil.NEW_NAME_IMG + DateUtil.formats('yyyyMMdd_HHmmss'); 50 } 51 } 52} 53