【问题标题】:calculate the day of the week计算星期几
【发布时间】:2020-04-04 17:44:39
【问题描述】:

我想用 javascript 写一个日历。对于日历,我使用 javascript 生成了一个表格,并且我想在一行中显示每个日期的星期几。但该表仅显示未定义。我不知道怎么了。

这是计算日期的函数:

var currentDay = function (currentMonth) {
var month_code = ["6", "2", "2", "5", "0", "3", "5", "1", "4", "6", "2", "4"];

var year_digit = currentYear - 2000;                         
var year_code = (year_digit + (year_digit / 4)) % 7;

currentDay = ((1 + month_code[currentMonth] + year_code) % 7) - 1;

return currentDay; }

我用公式计算一天:

("月份中的第几天" + 月份代码 + 年份代码) % 7

月份代码是固定的,位于“month_code”数组中。它从一月开始,到十二月结束。我可以用当前年份的最后两位数字计算年份代码。然后我们将这些除以 4。然后我们添加最后两位数。然后我们必须以 7 为模计算总和,我们就有了年份代码。

例如:(我使用日期,我写的问题:04.04.2020) 一个月中的一天:4 月码:5 年份代码: 2020 --> 20 ; 20/4 = 5; 5 +20 = 25; 25%7 = 4 --> 年份代码为 4

(4+5+4) % 7 = 6

现在我必须从结果中减去 1,因为数组以 0 而不是 1 开头。

var day_of_week = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
day_of_week[5]="Sat";

今天是星期六。

希望有人能帮助我

【问题讨论】:

标签: javascript html


【解决方案1】:

您没有使用Date 对象有什么原因吗?

使用日期对象,您可以通过调用 toLocaleString 并将选项 weekday 设置为 shortlong 来获取工作日。

const dateString = '05/23/2014';
const date = new Date(dateString);
console.log(`${dateString} was a ${date.toLocaleString('en-us', {weekday:'long'})}`);


const today = new Date();
console.log(`Today is a ${today.toLocaleString('en-us', {weekday:'short'})}`);

【讨论】:

    猜你喜欢
    • 2016-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多