如何找到星期几 - Java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18333099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:36:13  来源:igfitidea点击:

How to find which day of the week it is - Java

javadate

提问by Ethan Edwards

there has been a few other question which are pretty much the same, but i cant seem to get my bit of code to work. I get the user input which is there birthday dd/mm/yyyy. I'm ignoring leap years by the way. Im trying to determine what day of the week it was when the user was born. I have to determine how many days they were born from a certain date which in this case is Tuesday the 1st of January 1901. That's why ive done year-1901

还有一些其他问题几乎相同,但我似乎无法让我的代码工作。我得到了生日 dd/mm/yyyy 的用户输入。顺便说一下,我忽略了闰年。我试图确定用户出生时是一周中的哪一天。我必须确定他们从某个日期出生了多少天,在这种情况下是 1901 年 1 月 1 日星期二。这就是我这样做的原因year-1901

day=int day;

天=int day;

used a switch to determine how many days in each month which is represented by dayMonthso July has 31, feb has 28 etc.

使用开关来确定每个月有多少天,dayMonth因此 7 月有 31,2 月有 28 等。

year=int year;

年=int year;

String[] days =
         {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
howManyDays = ((year-1901)*365 + dayMonth + day - 1);       
whatDay = (howManyDays%7);
days[whatDay]

It works sometimes, but then sometimes it doesn't. Any help is appreciated, if any questions feel free to ask. Thanks in advance and hope it makes sense!

它有时有效,但有时却无效。任何帮助表示赞赏,如果有任何问题随时提出。提前致谢,希望它是有道理的!

回答by RedSonja

You can use Java Calendar.

您可以使用 Java 日历。

Calendar c = Calendar.getInstance();
c.set(year, month, day);

int day_of_week = c.get(Calendar.DAY_OF_WEEK);

This gives you an int which day of week it is, you can just provide an array to map with the "names" of the days.

这为您提供了一周中的哪一天的 int,您只需提供一个数组来映射日期的“名称”。

回答by Dileep

The Code you have used cannot be implemented in any standard date operations because there are many cases like leap year etc.

您使用的代码无法在任何标准日期操作中实现,因为有很多情况,例如闰年等。

Try to use java.util.Calendarfor date operations that needs to know the details like Week Days, Months etc.

尝试使用java.util.Calendar进行日期操作,这些操作需要了解周天、月等详细信息。

For Even More Complex date function Use JODA Calendar. Joda Calendar is fast and have a lot of operations like no of days between two days etc. You can Look into the above link for more details.

对于更复杂的日期函数,请使用JODA Calendar。Joda Calendar 速度很快,并且有很多操作,例如两天之间的天数等等。您可以查看上面的链接以获取更多详细信息。

For Now you can use this

现在你可以使用这个

     Calendar calendar = Calendar.getInstance();
     calendar.set(year, month, date) ;
     int i=calendar.get(Calendar.DAY_OF_WEEK);

Here the value of i will be from 1-7 for Sunday to Saturday.

在这里,周日到周六的 i 值将从 1 到 7。