As you can see, the user interface includes the surrounding month and date options in addition to the selected date. This means that I need to not only keep track of the current date, but I also need a way to conveniently figure out how many days are in the selected month and which months come before and after that selected month.
When I first looked at this design, I thought I was going to have to write a bunch of helper functions for this. But I didn’t have a lot of time, so I decided to see what JavaScript’s Date
object could do for me in this situation.
It turns out, the Date
object is well suited to solve this problem. I started out by just playing around with it in my browser console. I was surprised to find that the Date
object’s constructor method behaves in exactly the way I needed it to in order to easily get the required information.
The constructor method can be used in a few different ways. For this task, I created a date like so:
new Date(year, monthIndex, day)
The monthIndex
is the month’s order number starting from 0
instead of 1
.
To make it easier on myself, I created a hook and some setter functions to create new Date
objects each time the date changed:
const dateObj = new Date(2000, 0, 1);
const [date, setDate] = useState(dateObj);
const setMonth = month => {
const newDate = new Date(
date.getFullYear(),
month,
date.getDate()
);
setDate(newDate);
};
const setDay = day => {
const newDate = new Date(
date.getFullYear(),
date.getMonth(),
day
);
setDate(newDate);
};
const setYear = year => {
const newDate = new Date(
year,
date.getMonth(),
date.getDate()
);
setDate(newDate);
};
#programming #javascript-development #programming-tips #javascript #javascript-tips