Hello, React Native enthusiasts! Today, let's tackle a common scenario in app development – dealing with dates. Specifically, we'll dive into the simple yet crucial task of fetching the first and last day of a month.
Join me on this step-by-step journey, and soon you'll be seamlessly handling date logic in your React Native projects.
In this article, we'll see get first day and last day of the current month using Moment JS in React Native, and we'll see the startOf of the method using Moment JS and the endOf the method using Moment JS.
Assuming you have React Native set up, kick off a new project with:
expo init MonthDatesDemo
cd MonthDatesDemo
Install Moment.js using the following command:
npm install moment
Create a functional component and set up the initial state to handle the first and last day of the month:
import React,{useState} from 'react';
import { StyleSheet, Text, View} from 'react-native';
import moment from 'moment'
export default function App() {
return (
<View style={styles.container}>
<Text style={styles.date}>Start Date of Current Month</Text>
<Text style={styles.date}>{moment().startOf('month').format('YYYY-MM-DD hh:mm') }</Text>
<Text style={styles.date}>End Date of Current Month</Text>
<Text style={styles.date}>{moment().endOf('month').format('YYYY-MM-DD hh:mm') }</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
text: {
fontSize: 24,
},
date: {
fontSize: 24,
fontWeight: 'bold',
padding: 15
}
});
Run your Expo app using the following command:
expo start
And there you have it! Now, armed with a few simple steps and the magic of the Moment JS library, you can easily fetch the first and last day of the month in your React Native project.
So go ahead, implement these tricks, and keep rocking your React Native development journey! Happy coding!
You might also like:
- Read Also: How to Subtract Days in Date in React Native
- Read Also: How to Create Login Form using Spring Boot React
- Read Also: How to Create Moment JS Calendar in React Native
- Read Also: Laravel 10 REST API Authentication using Sanctum