javascript date为日期选择器构建一个react钩子

This week, I had to construct a date selector form in React that looks like this:

这周,我不得不在React中构造一个日期选择器表单,如下所示:

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.

当我第一次查看此设计时,我认为我将不得不为此编写一堆辅助函数。 但是我没有很多时间,所以我决定看看在这种情况下JavaScript的Date对象可以为我做什么。

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.

事实证明, Date对象非常适合解决此问题。 我刚开始在浏览器控制台中试用它。 我很惊讶地发现Date对象的构造方法的行为与我需要它的方式完全相同,以便轻松获取所需的信息。

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.

monthIndex是月份的订单号,从0而不是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:

为了使自己更轻松,我创建了一个钩子和一些setter函数,以便在每次更改Date时创建新的Date对象:

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);
};

Now that I have a way to create a date and change it, I need to figure out how to 1) translate the month index into a three-letter month name and 2) display the months and days that come before and after the selected month and day.

现在,我已经有了创建日期和更改日期的方法,我需要弄清楚如何1)将月份索引转换为三个字母的月份名称,以及2)显示所选月份前后的月份和日期。和一天。

Solving the first problem is simple. I just created an array with the abbreviations. Then, to display the before/after months, I added some conditional statements to adjust the index if it’s invalid.

解决第一个问题很简单。 我刚刚用缩写创建了一个数组。 然后,为了显示之前/之后的月份,我添加了一些条件语句来调整索引(如果无效)。

That way, to display the month name that comes two months before the selected date’s month — in the image at the top, this would be ‘FEB’ — I would just need to pass selectedMonthIndex — 2 in and the function will do the rest:

这样,要显示所选日期月份的前两个月的月份名称(在顶部的图像中为“ FEB”),我只需要传递selectedMonthIndex — 2 ,剩下的将由该函数完成:

const getMonth = index => {
let newMonthIndex = index;
if (index < 0) newMonthIndex += 12;
else if (index > 11) newMonthIndex -= 12; const monthList = [ ‘JAN’, ‘FEB’, ‘MAR’, ‘APR’, ‘MAY’, ‘JUN’, ‘JUL’, ‘AUG’, ‘SEP’, ‘OCT’, ‘NOV’, ‘DEC’, ]; return monthList[newMonthIndex];
};

That takes care of the months. Now on to the days.

这需要几个月的时间。 现在开始。

To figure out which days to display, I need to calculate how many days are in the currently selected month. Building this from scratch would take a lot of work. Luckily, there’s a little bit of JavaScript magic already built in to take care of this.

为了弄清楚要显示的日期,我需要计算当前所选月份中有多少天。 从头开始构建它会花费很多工作。 幸运的是,已经内置了一些JavaScript魔术来解决此问题。

The cool part about the Date object’s constructor method is that it corrects any mistakes you make in a way that is pretty convenient. For example, if you paste this code in your console:

有关Date对象的构造方法的很酷的部分是,它以非常方便的方式纠正了您犯的任何错误。 例如,如果将以下代码粘贴到控制台中:

new Date(2020, 0, 32)

The returned date will be February 1, 2020. The Date object knows January 2020 had 31 days. Therefore, in JavaScript, January 32 is the same as February 1. Conversely, February 0 is the same as January 31.

返回的日期将是2月1日,2020年的Date对象知道2020年1月有31天。 因此,在JavaScript中,1月32日与2月1日相同。相反,2月0日与1月31日相同。

So, given a month index, you can calculate how many days are in that month by doing this:

因此,给定一个月索引,您可以通过执行以下操作来计算该月中有多少天:

const maxDay = new Date(year, monthIndex + 1, 0)

The zeroth day of the next month is the last day of the current month. Using that, I can write a function similar to the above getMonth() to calculate my before/after days:

下个月的第零天是当月的最后一天。 使用它,我可以编写类似于上述getMonth()的函数来计算我的前/后天:

const getDay = dayNum => {
const fullMaxDate = new Date(
date.getFullYear(),
date.getMonth() + 1,
0
);
const maxDay = fullMaxDate.getDate(); if (dayNum < 1) return maxDay - dayNum;
if (dayNum > maxDay) return dayNum - maxDay;
return dayNum;
};

Just as before, I can simply pass selectedDay — 2 into this function, and it will do the rest of the work calculating the correct day to display.

和以前一样,我可以简单地将selectedDay — 2传递给此函数,它将完成剩下的工作,计算要显示的正确日期。

Ultimately, I need to format this date as YYYY-MM-DD when I send it over to the back end. The Date object doesn’t have a built-in method for this, but it does provide a toISOString() method that contains this format at the beginning of the returned string. To correctly format my date, I just sliced off those first 10 characters:

最终,当我将其发送到后端时,需要将该日期格式设置为YYYY-MM-DDDate对象没有为此的内置方法,但确实提供了toISOString()方法,该方法在返回的字符串的开头包含此格式。 为了正确格式化日期,我只切了前10个字符:

const format = () => date.toISOString().slice(0, 10);

And that was all I needed to build the UI component shown at the top of this article. Using JavaScript’s built-in Date object, I let JavaScript do all the tricky date calculations and wrapped its API in my own, easy-to-use functions.

这就是构建本文顶部所示的UI组件所需要的。 使用JavaScript的内置Date对象,我可以让JavaScript执行所有棘手的日期计算,并将其API封装在我自己的易于使用的函数中。

The great thing about this is that, on top of making the calculations simple, the date selector will account for leap years without any extra work.

这样做的好处是,除了使计算简单之外,日期选择器还将说明leap年,而无需进行任何额外工作。

翻译自: https://levelup.gitconnected.com/javascript-date-building-a-react-hook-for-date-selector-b07955c4d7bd

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值