React Js Get First and Last Day of Current Week
React Js Get First and Last Day of Current Week :In this tutorial, we will walk you through how to use React.js to get the first and last day of the current week. This can be particularly useful when building date-related features in your web applications. We'll explain the code step by step and provide a working example.
Thanks for your feedback!
Your contributions will help us to improve service.
Output of above Code
Code Explanation
Here's a breakdown of the code used in the React component:
We start by importing the useState
function from the React library and defining a functional component called App
. Inside App
, we obtain the current date using the Date
object and get the day of the week (0 for Sunday, 1 for Monday, and so on) using getDay()
.
To calculate the first day of the current week, we create a new Date
object named firstDayOfWeek
, which is a copy of the current date. We then subtract the current day of the week from the date to go back to the beginning of the week.
Similarly, we calculate the last day of the week by creating a new Date
object named lastDayOfWeek
and adding the number of days needed to reach the end of the week, which is 6 days minus the current day
To display the first and last day of the week as strings, we convert them to ISO date strings and extract the first 10 characters to get the date portion
Finally, we render a simple user interface within the return
statement. This UI displays the title, "React Js Get First and Last Day of the Current Week," along with the calculated first and last days of the week.