如何从Date对象中提取星期几和星期几?

普拉纳夫

在一个 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>
            ))
        }
    </>
)

获取输出为:

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)

以下是codesandbox链接供参考:https ://codesandbox.io/s/material-demo-forked-jotw6

菜鸟书呆子

在这种情况下,有像getDay()getDate()这样的方法很有用。以下是我们如何实现您的目标。

  • currDay() 将数字中的天数转换为字符串格式的天数。
  • 通过使用getDay()and 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如果我错过了什么,请告诉我。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章