【问题标题】:JavaScript Date Format: Format The Day e.x (Mon)JavaScript 日期格式:格式化日期 e.x(星期一)
【发布时间】:2021-01-04 07:11:54
【问题描述】:

我正在尝试制作一个基本的周历。这些数字工作正常,但我不知道如何准确地做到这一点,以获取字符串中的日子。例如我需要这种格式: 今天是:星期一 明天是:星期二

我尝试了一些代码,但我所能做的就是这样写一天: 今天是:星期一。

那么有什么选项可以让“星期一”变成“星期一”吗?

我也需要这样做,以获得明天和昨天的价值。 我是说: 昨天:太阳 今天:周一 明天:周二

但是当我尝试制作它时,出现了错误。知道如何使它可行吗?

顺便说一下我的尝试:

var options = {
  weekday: 'long'
};
var today = new Date();
var option = {
  weekday: 'long'
};
var tomorrow = new Date();
var todaya1 = tomorrow.getDate() + 1;
document.getElementById("today").innerHTML = today.toLocaleDateString("en-US", options);
document.getElementById("tomorrow").innerHTML = todaya1.toLocaleDateString("en-US", option);
#today {
  color: red;
}
<span id="today"></span>
<span id="tomorrow"></span>

【问题讨论】:

    标签: javascript html css date format


    【解决方案1】:

    您有控制台错误,因为tomorrow.getDate() + 1; 不是日期对象

    你需要创建两个日期对象

    另外,如果它们相同,您只需要一组选项

    const options = { weekday: 'short' };
    
    var today = new Date();
    var tomorrow = new Date()
    tomorrow.setDate(tomorrow.getDate() + 1);
    
    document.getElementById("today").innerHTML = today.toLocaleDateString("en-US", options);
    document.getElementById("tomorrow").innerHTML = tomorrow.toLocaleDateString("en-US", options);
    #today {
      color: red;
    }
    <span id="today"></span>
    <span id="tomorrow"></span>

    【讨论】:

      【解决方案2】:

      const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
      const todayDate = new Date();
      const todayDay = days[todayDate.getDay()];
      const tomorrowDate = new Date(todayDate);
      tomorrowDate.setDate(tomorrowDate.getDate() + 1);
      const tomorrowDay = days[tomorrowDate.getDay()];
      
      const todayEl = document.getElementById('today');
      const tomorrowEl = document.getElementById('tomorrow');
      
      todayEl.textContent = todayDay;
      tomorrowEl.textContent = tomorrowDay;
      <span id="today"></span>
      <span id="tomorrow"></span>

      【讨论】:

      • Actullay 使用{ weekday: 'shrort' }toLocaleDateString 是更好的方法。
      猜你喜欢
      • 1970-01-01
      • 2010-11-03
      • 2014-10-08
      • 2023-03-29
      • 1970-01-01
      • 2012-05-24
      • 1970-01-01
      • 2022-01-18
      相关资源
      最近更新 更多