JavaScript 中的星期几数字表示?
在本文中,我们将学习如何在 JavaScript 中使用适当的示例将星期几表示为数字。
为了获取星期几的数字表示,JavaScript 提供了 `getDay()` 方法。`getDay()` 是 Date 对象的一个方法。`getDay()` 方法返回 0 到 6 之间的数值。例如,星期日 = 0,星期一 = 1,星期二 = 2,星期三 = 3,以此类推。
为了更好地理解,让我们深入了解 JavaScript 中 `getDay()` 方法的语法和用法。
语法
`getDay()` 方法的语法如下:
dateObject.getDay();
其中,`dateObject` 是由日期创建的对象。此方法返回 0 到 6 之间的数字(0 – 星期日,1 – 星期一,2 – 星期二,3 – 星期三,4 – 星期四,5 – 星期五,6 – 星期六)。
示例 1
这是一个示例程序,演示如何使用 `getDay()` 方法在 JavaScript 中获取当前日期的星期几数字表示。
<!DOCTYPE html>
<html>
<head>
<title>Weekday as a number in JavaScript</title>
</head>
<body style="text-align : center">
<h3>Weekday as a number in JavaScript</h3>
<p>The returned value is an integer, which is the day of the week (0 to 6).
i.e. 0 - Sunday
1 - Monday
....
6 - Saturday .
</p>
<p id="output"></p>
<script>
const date = new Date(); //Get the day of the week of current date
const day = date.getDay();
document.getElementById("output").innerHTML = 'Week day as a number for the date : ' + date + ' is : ' + day;
</script>
</body>
</html>
执行上述代码后,将生成以下输出。
示例 2
这是一个示例程序,演示如何使用 `getDay()` 方法在 JavaScript 中获取用户指定日期的星期几数字表示。
<!DOCTYPE html>
<html>
<head>
<title>Weekday as a number in JavaScript</title>
</head>
<body style="text-align : center">
<h3>Weekday as a number in JavaScript</h3>
<p>The returned value is an integer, which is the day of the week (0 to 6).
i.e. 0 - Sunday
1 - Monday
....
6 - Saturday .
</p>
<p id="output"></p>
<script>
const date = new Date("January 4 2001 04:04:04"); //Get the day of the week of particular date mentioned by the user
const day = date.getDay();
document.getElementById("output").innerHTML = 'Week day as a number for the date : ' + date + ' is : ' + day;
</script>
</body>
</html>
执行上述代码后,将生成以下输出。
示例 3
这是一个示例程序,定义一个基于 Zeller 算法的用户自定义函数,用于在 JavaScript 中获取星期几的数字表示。
<!DOCTYPE html>
<html>
<head>
<title>Weekday as a number in JavaScript</title>
</head>
<body style="text-align : center">
<h3>Weekday as a number in JavaScript</h3>
<p>The returned value is an integer, which is the day of the week (0 to 6).
i.e. 0 - Sunday
1 - Monday
....
6 - Saturday .
</p>
<p id="output"></p>
<script>
// Without using Date() and getDay()
var dd,mm,yyyy;
function calculateDay(dd, mm, yyyy) {
const weekday = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
const indexes_of_weekday = [0,1,2,3,4,5,6];
if (mm< 3) {
mm += 12;
yyyy--;
}
var h = (dd + parseInt(((mm + 1) * 26) / 10) + yyyy + parseInt(yyyy / 4) + 6 * parseInt(yyyy / 100) + parseInt(yyyy / 400) - 1) % 7;
return indexes_of_weekday[h];
}
var day = calculateDay(23,06,2022);
document.getElementById("output").innerHTML = 'The day is : ' + day;
</script>
</body>
</html>
执行上述代码后,将生成以下输出。
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP