[英]How to extract day of week and day from a Date object?
在一个 React 项目中,我想设置这个月内的所有日期和日期。 就像我想将其提取为Sat 13
、 Sun 14
、 Mon 15
......等等。 最好的解决方案是什么?
代码参考如下:
Date.prototype.addDays = function (days) {
var dat = new Date(this.valueOf());
dat.setDate(dat.getDate() + days);
return dat;
};
const getDates = (startDate, stopDate) => {
var dateArray = new Array();
var currentDate = startDate;
while (currentDate <= stopDate) {
dateArray.push(currentDate);
currentDate = currentDate.addDays(1);
}
return dateArray;
};
const dateArray2 = getDates(new Date(), new Date().addDays(30));
useEffect(() => {
setNewDate(dateArray2);
setCurrentMonth(monthNames[d.getMonth()]);
}, []);
return (
<>
{
newDate.map((data) => (
<h2>{newDate.toString()}</h2>
))
}
</>
)
获取 output 为:
Sat Mar 13 2021 14:41:01 GMT+0530 (India Standard Time)
Sun Mar 14 2021 14:41:01 GMT+0530 (India Standard Time)
Mon Mar 15 2021 14:41:01 GMT+0530 (India Standard Time)
以下是codeandbox链接供参考: https://codesandbox.io/s/material-demo-forked-jotw6
有像getDay()
和getDate()
这样的方法在这种情况下很有用。 以下是我们如何实现您想要做的事情。
currDay()
将数字中的天数转换为字符串格式的天数。getDay()
和getDate()
,我们可以只获取星期几和日期。const currday = (dayInDig) => {
if(dayInDig === 1){
return "Mon";
}
else if(dayInDig === 2){
return "Tue";
}
else if(dayInDig === 3){
return "Wed";
}
else if(dayInDig === 4){
return "Thurs";
}
else if(dayInDig === 5){
return "Fri";
}
else if(dayInDig === 6){
return "Sat";
}
else{
return "Sun";
}
}
return (
<>
<h3>{currentMonth}</h3>
{newDate.map((data) => (
<h2>{currday(data.getDay())} {data.getDate()}</h2>
))}
</>
);
这是Codesandbox 。 如果我错过了什么,请告诉我。
如果Date.toString()
方法的格式如您所愿,我只需使用split()
来提取所需日期中的条目。
const getFormattedDate = (date) => {
const splitString = date.toString().split();
return `${splitString[0]} ${splitString[2]}`
}
或者,如果您希望更改日期(例如,获取全名),您可以创建一个数组,然后数组的索引将匹配日期编号:
const daysOfWeek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
const getDayOfWeek = (date) => daysOfWeek[date.getDay()]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.