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