📌  相关文章
📜  javascript get day - Javascript (1)

📅  最后修改于: 2023-12-03 15:01:37.601000             🧑  作者: Mango

JavaScript Get Day

JavaScript is a popular programming language used for creating interactive web pages and web applications. One common task in web development is getting the day of the week for a given date. In this article, we will explore how to get the day in JavaScript.

The Date Object

In JavaScript, the Date object is used to work with dates and times. To get the current date and time, we can simply create a new Date object with no arguments:

const now = new Date();

This will create a new Date object representing the current date and time.

Getting the Day of the Week

Once we have a Date object, we can use its getDay() method to get the day of the week. The getDay() method returns a number representing the day of the week, where 0 represents Sunday, 1 represents Monday, and so on.

const now = new Date();
const dayOfWeek = now.getDay(); // Returns a number between 0 and 6

To get the actual string representation of the day of the week, we can use an array of strings:

const daysOfWeek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
const dayOfWeekString = daysOfWeek[now.getDay()]; // Returns a string representation of the day of the week
Conclusion

Getting the day of the week in JavaScript is a simple task using the Date object's getDay() method. By using an array of strings, we can easily convert the resulting number to a string representation of the day of the week.