import React, { useState } from "react";
import {
View,Text,TextInput,
Button,StyleSheet,
} from "react-native";
const AgeCalculator = () => {
const [birthdate, setBirthdate] =
useState("");
const [age, setAge] = useState("");
const calculateAge = () => {
const currentDate = new Date();
const birthdateArray =
birthdate.split("/");
if ( birthdateArray.length === 3 ) {
const day = parseInt(
birthdateArray[0], 10);
const month = parseInt(
birthdateArray[1], 10);
const year = parseInt(
birthdateArray[2],10);
if (!isNaN(day) &&
!isNaN(month) &&
!isNaN(year)) {
const birthDate =
new Date(year,month - 1,day);
// Calculate the age
const ageInMilliseconds =
currentDate - birthDate;
const ageInYears =
ageInMilliseconds /
(1000 * 60 * 60 * 24 * 365.25);
const ageYears =
Math.floor(ageInYears );
const ageMonths =
Math.floor(
(ageInYears - ageYears) * 12);
const ageDays =
Math.floor(
(ageInYears - ageYears) *
365.25 - ageMonths * 30.44);
setAge(
`Your age is : ${ageYears} years, ${ageMonths} months, and ${ageDays} days.`);
return;}}
setAge(
"Please enter a valid date in the format: dd/mm/yyyy");};
return (
<View style={styles.container}>
<View style={styles.logo}>
<Text
style={
styles.logotext}>
{" "}
GeekforGeeks{" "}
</Text>
</View>
<Text style={styles.header}>
Age Calculator
</Text>
<TextInput
style={styles.input}
placeholder="Enter your birthdate (dd/mm/yyyy)"
onChangeText={(text) =>
setBirthdate(text)}/>
<Button
title="Calculate Age"
onPress={calculateAge}/>
<Text style={styles.result}>
{age}
</Text>
</View>
);};
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
backgroundColor: "#f0f0f0",
},
logo: {
width: 150,
height: 150,
backgroundColor: "lightgreen",
borderRadius: 150,
marginTop: 50,
},
logotext: {
alignItems: "center",
justifyContent: "center",
marginLeft: 25,
marginTop: 60,
fontWeight: "bold",
fontSize: 15,
},
header: {
fontSize: 24,
marginBottom: 20,
},
input: {
width: 200,
height: 40,
borderColor: "gray",
borderWidth: 1,
paddingLeft: 10,
marginBottom: 10,
},
result: {
fontSize: 20,
marginTop: 20,
},
});
export default AgeCalculator;