Docs
Examples
Age Calculator

Age Calculator Example

import React, {useState} from 'react';
import {View, Text, SafeAreaView, StyleSheet} from 'react-native';
import {BasicToolbar} from "@components";
import { Button } from 'react-native-paper';
import DateTimePickerModal from "react-native-modal-datetime-picker";
 
 
// ChatGPT
function calculateAge(birthDay, today) {
  let years = today.getFullYear() - birthDay.getFullYear();
  let months = today.getMonth() - birthDay.getMonth();
  let days = today.getDate() - birthDay.getDate();
 
  // Check if the birth date has not been reached this month
  if (days < 0) {
    months--;
    const previousMonth = new Date(today.getFullYear(), today.getMonth() - 1, 0);
    days += previousMonth.getDate();
  }
 
  // Check if the birth month has not been reached this year
  if (months < 0) {
    years--;
    months += 12;
  }
  return {years, months, days};
}
 
 
 
function App({exit}) {
  const [datePickerFor, setDatePickerFor] = useState(null)
  const [birthDate, setBirthDate] = useState(null)
  const [today, setToday] = useState(new Date())
 
  const selectDate = (date) => {
    if (datePickerFor === "birth"){
      setBirthDate(date)
    } else {
      setToday(date)
    }
    setDatePickerFor(null)
  }
 
  const age = birthDate && today ? calculateAge(birthDate, today) : null
 
  return (
    <SafeAreaView style={{flex: 1}}>
      <View style={{flex: 1}}>
        <BasicToolbar title="Age Calculator" exit={exit} />
        <View style={{flex: 1, padding: 20, alignItems: "center", justifyContent: "center"}}>
          <Text style={{fontWeight: "bold", fontSize: 24}}>Your birthday</Text>
          <Button style={styles.dateButton} icon="calendar" onPress={() => setDatePickerFor("birth")}>
            <Text style={{fontSize: 18}}>{birthDate == null ? "Select Date" : birthDate.toDateString()}</Text>
          </Button>
          <Text style={{fontWeight: "bold", fontSize: 24}}>Today is</Text>
          <Button style={styles.dateButton} icon="calendar" onPress={() => setDatePickerFor("today")}>
            <Text style={{fontSize: 18}}>{today.toDateString()}</Text>
          </Button>
          { age && (
            <View style={{alignItems: "center"}}>
              <Text style={{fontWeight: "bold", fontSize: 24, marginBottom: 8}}>Your age is</Text>
              <Text style={{fontSize: 16}}>{age.years} years</Text>
              <Text style={{fontSize: 16}}>{age.months} months</Text>
              <Text style={{fontSize: 16}}>{age.days} days</Text>
            </View>
          )}
        </View>
        <DateTimePickerModal
          date={datePickerFor === "today" ? today : (birthDate || new Date())}
          isVisible={datePickerFor != null}
          mode="date"
          onConfirm={selectDate}
          onCancel={() => setDatePickerFor(null)}
        />
      </View>
    </SafeAreaView>
  );
}
 
const styles = StyleSheet.create({
  dateButton: {
    marginVertical: 10,
  }
})
 
export default App;