JavaScript日期格式:格式化日期e.x(星期一)



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

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

那么,是否有任何选择使";星期一";至";星期一"?

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

但当我试图做到这一点时,出现了一个错误。知道如何使其可行吗?

顺便说一句,这是我的尝试:

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>

您有控制台错误,因为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>

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>

相关内容

最新更新