如何使用 React Native 一起显示回历和公历日期

问题描述 投票:0回答:1

我正在尝试显示回历和公历日期。然而它只显示公历。

这是代码。

图书馆

import { Calendar } from 'react-native-calendars';
import moment from 'moment-hijri';
import HijriDate from 'hijri-date';

挂钩及其他

const [selectedDate, setSelectedDate] = useState(moment().format('iYYYY-iM-iD'));
const [hijriDate, setHijriDate] = useState('');

useEffect(() => {
    const date = new HijriDate();
    const monthNames = [
      'Muharram',
      'Safar',
      'Rabi al-Awwal',
      'Rabi al-Thani',
      'Jumada al-Awwal',
      'Jumada al-Thani',
      'Rajab',
      'Shaaban',
      'Ramadan',
      'Shawwal',
      'Dhu al-Qidah',
      'Dhu al-Hijjah',
    ];
    const month = monthNames[date.getMonth() - 1];
    const formattedDate = `${date.getDate()} ${month}, ${date.getFullYear()}`;

    setHijriDate(formattedDate);
  }, []);

自定义标题

 const renderHeader = (date) => {
    const gregorianDate = moment(date.dateString).format('MMMM, YYYY');
    return (
      <View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
        <Text style={{ color: COLORS.green, fontSize: 25 }}>{gregorianDate}</Text>
        <Text style={{ color: COLORS.green, fontSize: 25 }}>{hijriDate}</Text>
      </View>
    );
  };

日历

<Calendar
            markingType="custom"
            // selectedDate={moment()}
            // markedDates={markedDates}
            onDayPress={onDayPress}
            style={{ marginHorizontal: 10, marginVertical: 10 }}
            theme={{
              calendarBackground: COLORS.white,
              textSectionTitleColor: '#b6c1cd',
              selectedDayBackgroundColor: '#00adf5',
              selectedDayTextColor: '#ffffff',
              todayTextColor: '#00adf5',
              dayTextColor: '#2d4150',
              textDisabledColor: '#d9e1e8',
              dotColor: '#00adf5',
              selectedDotColor: '#ffffff',
              arrowColor: 'orange',
              monthTextColor: 'white',
              indicatorColor: 'blue',
              textDayFontFamily: 'monospace',
              textMonthFontFamily: 'monospace',
              textDayHeaderFontFamily: 'monospace',
              textDayFontSize: 16,
              textMonthFontSize: 16,
              textDayHeaderFontSize: 16,
            }}

            monthTextColor={'red'}
            renderHeader={(date) => {
              // const monthName = moment(date.dateString).format('iYYYY iMMMM iDD');
              return (
                <View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
                  <Text style={{ color: COLORS.green, fontSize: 25 }}>{hijriDate}</Text>
                </View>
              );
            }}
          />

我尝试了其他可能的方法,例如转换每天的日期,然后尝试将其显示在未定义的公历日期下方。

我需要帮助来显示回历和公历日期。

我问了chatGpt,但没有用。

react-native momentjs gregorian-calendar hijri react-native-calendars
1个回答
0
投票

这就是我解决问题的方法

import React, { useEffect, useState } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import moment from 'moment-hijri';

const getIslamicMonthDays = () => {
    const hijriDate = moment() as any; // Current Hijri date
    const currentYear = hijriDate.iYear();
    const currentMonth = hijriDate.iMonth();

const daysInMonth = hijriDate.iDaysInMonth(); // Get days in the Hijri month
const firstDayOfMonth = moment(`${currentYear}-${currentMonth + 1}-01`, 'iYYYY-iM-iD').day();

let daysArray = [];
for (let i = 0; i < firstDayOfMonth; i++) {
    daysArray.push(null); // Empty cells for days before the first day
}
for (let i = 1; i <= daysInMonth; i++) {
    daysArray.push(i);
}

return { daysArray, currentMonth, currentYear };
};

const IslamicCalendar = () => {
    const [calendarData, setCalendarData] = useState(getIslamicMonthDays());

useEffect(() => {
    setCalendarData(getIslamicMonthDays());
}, []);

const { daysArray, currentMonth, currentYear } = calendarData;
const daysOfWeek = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

return (
    <View style={styles.calendarContainer}>
        <Text style={styles.monthText}>{`Month: ${currentMonth + 1} Year: ${currentYear} AH`}</Text>
        <View style={styles.daysOfWeekContainer}>
            {daysOfWeek.map((day, index) => (
                <Text key={index} style={styles.dayOfWeek}>
                    {day}
                </Text>
            ))}
        </View>
        <View style={styles.daysContainer}>
            {daysArray.map((day, index) => (
                <Text key={index} style={day ? styles.day : styles.emptyDay}>
                    {day || ''}
                </Text>
            ))}
        </View>
    </View>
);
};

const styles = StyleSheet.create({
    calendarContainer: {
        padding: 16,
        backgroundColor: '#f9f9f9',
        borderRadius: 8,
        alignItems: 'center',
        marginVertical: 20,
    },
    monthText: {
        fontSize: 18,
        fontWeight: 'bold',
        marginBottom: 10,
        color: '#033D2F',
    },
    daysOfWeekContainer: {
        flexDirection: 'row',
        justifyContent: 'space-around',
        width: '100%',
        marginBottom: 10,
    },
    dayOfWeek: {
        flex: 1,
        textAlign: 'center',
        fontWeight: 'bold',
        color: '#033D2F',
    },
    daysContainer: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        width: '100%',
    },
    day: {
        width: '14%',
        textAlign: 'center',
        padding: 10,
        color: '#033D2F',
        borderRadius: 5,
        backgroundColor: '#D9B12B',
        marginVertical: 2,
    },
    emptyDay: {
        width: '14%',
        textAlign: 'center',
        padding: 10,
        color: 'transparent',
        backgroundColor: 'transparent',
    },
});

export default IslamicCalendar;

现在在您想要调用的地方调用 IslamCalendar

如果您在导入 moment-hijri 时遇到错误,即使在运行后

npm install moment-hijri moment

然后创建一个 moment-hijri.d.ts 并添加以下代码

declare module 'moment-hijri' {
    import moment from 'moment';
    export = moment;

    interface Moment {
        iYear(year?: number): number | Moment;
        iMonth(month?: number): number | Moment;
        iDate(date?: number): number | Moment;
        iDaysInMonth(): number;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.