Mohsin S S
Mohsin S S

Reputation: 63

How to show Hijri and Gregorian dates together using react native

I'm trying to display both hijrj and gregorian dates. However it only shows gregorian.

This is the code.

Libraries

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

Hooks and other

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);
  }, []);

Custom header

 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

<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>
              );
            }}
          />

I tried other possible ways like converting the date for each day and then tried showing it below the gregorian date getting undefined.

I need an help to show both hijri and gregorian dates.

I asked chatGpt but to no use.

Upvotes: 1

Views: 1020

Answers (1)

Blessing Mwiti
Blessing Mwiti

Reputation: 1

this is how i solved mine (shows islamic calendar only)

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;

now call IslamicCalendar where you would want to call it

if you get error in importing moment-hijri, even after running

npm install moment-hijri moment

then create a moment-hijri.d.ts and add the following code

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;
    }
}

Upvotes: 0

Related Questions