简体   繁体   English

我怎样才能得到给定日期的星期几?

[英]How can I get the day of the week with date given?

I want to get the day of the week (ex: Monday, Tuesday, etc.) with a random given date.我想得到一个随机给定日期的星期几(例如:星期一、星期二等)。 This is my code:这是我的代码:

 function dayOfWeek (date) { var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']; return day var day = date(i); document.write("get.day(): " + day.getDay()); } var date1 = 11/19/2001; console.log(dayOfWeek(date1)); var date2 =12/19/1969; console.log(dayOfWeek(date2));

There were quite a few things that were wrong with your code.您的代码有很多问题。

First is that you were incorrectly using a return statement.首先是您错误地使用了 return 语句。 Any code after your return statement in the dayOfWeek function won't be run.您在dayOfWeek function 中的 return 语句之后的任何代码都不会运行。

Also, var date1 = 11/19/2001 is 100% not what you think it is.此外, var date1 = 11/19/2001是 100% 不是您认为的那样。 As it is now, it's two division operations, and not a string or date object.就像现在一样,它是两个除法运算,而不是字符串或日期 object。 Notice in my code there are quotes surrounding the date value.请注意,在我的代码中,日期值周围有引号。

 function dayOfWeek (date) { const days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']; return days[date.getDay()]; } var date1 = new Date('11/19/2001'); console.log(dayOfWeek(date1)); var date2 = new Date('12/19/1969'); console.log(dayOfWeek(date2));

You may want to look into DateTimeFormat and the formatToParts if you plan on allowing for other languages.如果您打算允许其他语言,您可能需要查看DateTimeFormatformatToParts

Hope this helps希望这可以帮助

Your code works fine - But as noted from above, you have syntax errors and are actually using division (math) operators.您的代码工作正常 - 但如上文所述,您有语法错误并且实际上正在使用除法(数学)运算符。

There's an easy way to get the date though.不过,有一种简单的方法可以获取日期。

From a library I built called Date.js - It allows you to get all dates using 1 function.从我构建的一个名为Date.js的库中 - 它允许您使用 1 function 获取所有日期。

Here's a live example of Date.js:这是 Date.js 的一个活生生的例子:

 console.log("Current time:", date.js.time()); console.log("Current millisecond:", date.js.millisecond()); console.log("Current second:", date.js.second()); console.log("Current minute:", date.js.minute()); console.log("Current hour:", date.js.hour()); console.log("Current day:", date.js.day()); console.log("Current week:", date.js.week()); console.log("Current month:", date.js.month()); console.log("Current three-letter month:", date.js.tlmonth()); console.log("Current season:", date.js.season());
 <:DOCTYPE html> <html> <head> <script type="text/javascript" src="https.//cdn.jsdelivr.net/gh/Parking-Master/Date.js@latest/date.min.js"></script> </head> <body> </body> </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM