• 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 i18n from '@ohos.i18n';
17
18const YEAR_CONVERT: number = 2697;
19const YEAR_CYCLE: number = 60;
20const LUNAR_MONTH = ['正', '二', '三', '四', '五', '六', '七', '八', '九', '十', '冬', '腊'];
21const LUNAR_DAY = ['初一', '初二', '初三', '初四', '初五', '初六', '初七', '初八', '初九', '初十', '十一', '十二', '十三', '十四',
22'十五', '十六', '十七', '十八', '十九', '廿十', '廿一', '廿二', '廿三', '廿四', '廿五', '廿六', '廿七', '廿八', '廿九', '三十',
23'三一'];
24const NUM_CHAR = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
25
26class CalendarUtil {
27  //公历转农历
28  getLunarDate(date: Date) {
29    let calendar = i18n.getCalendar('zh-CN', 'chinese');
30    calendar.setTime(date);
31    const lunarMonth = calendar.get('month');
32    const lunarDay = calendar.get('date');
33    let lunarYear = calendar.get('era') * YEAR_CYCLE + calendar.get('year') - YEAR_CONVERT;
34    return {
35      year: lunarYear,
36      month: lunarMonth,
37      day: lunarDay
38    }
39  }
40
41  formatLunarDate(lunar: any) {
42    if (!lunar) {
43      return '';
44    }
45    let result: string = '';
46    if (lunar.year) {
47      result += `${lunar.year}年`
48    }
49    if (lunar.month != undefined) {
50      result += `${LUNAR_MONTH[lunar.month]}月`
51    }
52    if (lunar.day) {
53      result += ` ${LUNAR_DAY[lunar.day - 1]}`
54    }
55    return result;
56  }
57}
58
59export default new CalendarUtil();
60
61
62
63
64