java 返回给定日期的星期几的 getDay() 方法不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48820696/
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
getDay() method to return day of the week for a given date not works
提问by Said
I'm trying to complete the task named Java Date and Timeon HackerRank.
我正在尝试在 HackerRank 上完成名为Java 日期和时间的任务。
Task
任务
You are given a date. You just need to write the method, getDay, which returns the day on that date.For example, if you are given the date, August 14th 2017, the method should return MONDAY as the day on that date.
给你一个约会。您只需要编写方法 getDay,该方法返回该日期的日期。例如,如果给定日期 2017 年 8 月 14 日,则该方法应返回 MONDAY 作为该日期的日期。
I tried my best to do the task but I get either the null
result or NullPointerException
error. I wonder where do I do wrong. Below is my code:
我尽力完成任务,但我得到了null
结果或NullPointerException
错误。我想知道我哪里做错了。下面是我的代码:
Thanks in advance!
提前致谢!
My Code:
我的代码:
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String month = in.next();
String day = in.next();
String year = in.next();
System.out.println(getDay(day, month, year));
}
public static String getDay(String day, String month, String year) {
Calendar cal = Calendar.getInstance();
cal.set(Integer.valueOf(year), (Integer.valueOf(month) - 1), Integer.valueOf(day));
return cal.getDisplayName(cal.get(Calendar.DAY_OF_WEEK), Calendar.LONG, Locale.getDefault());
}
}
回答by Elliott Frisch
Your return
is off; you don't want cal.get
in the first column of cal.getDisplayName
. Currently, I get the month name with your code. Change that to
你return
关机了;你不想cal.get
在cal.getDisplayName
. 目前,我使用您的代码获取月份名称。将其更改为
return cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.getDefault());
And call it like
并称之为
public static void main(String[] args) {
System.out.println(getDay("14", "8", "2017"));
}
And I get (as expected)
我得到(如预期)
Monday
In new code, I would preferthe new classes in java.time
(Java 8+), and a DateTimeFormatter
- like,
在新代码中,我更喜欢java.time
(Java 8+) 中的新类,以及DateTimeFormatter
- 之类的,
public static String getDay(String day, String month, String year) {
int y = Integer.parseInt(year), m = Integer.parseInt(month), d = Integer.parseInt(day);
return java.time.format.DateTimeFormatter.ofPattern("EEEE")
.format(LocalDate.of(y, m, d));
}
回答by Ravi Solanki
java.time.LocalDate
java.time.LocalDate
The modern approach uses the java.timeclasses.
现代方法使用java.time类。
- Import
java.time.*
to accessLocalDate
&DayOfWeek
classes. - Write
getDay
method which should be static because it is called in main method. - Retrieve localDate by using
of
method which takes 3 arguments in "int" format. - convert the
getDay
method arguments in int format. - finally retrieve name of that day using
getDayOfWeek
method.
- 导入
java.time.*
访问LocalDate
和DayOfWeek
类。 - Write
getDay
方法应该是静态的,因为它是在 main 方法中调用的。 - 通过使用采用
of
“int”格式的 3 个参数的方法检索 localDate 。 - 将
getDay
方法参数转换为int 格式。 - 最后使用
getDayOfWeek
方法检索当天的名称。
There is one video on this challenge. Java Date and Time Hackerrank
有一个关于这个挑战的视频。 Java 日期和时间黑客排名
LocalDate // Represent a date-only value, without time-of-day and without time zone.
.of( 2018 , 1 , 23 ) // Pass year-month-day, 1-12 for January-December.
.getDayOfWeek() // Obtain a `DayOfWeek` enum object.
.getDisplayName( // Automatically localize the name of the day-of-week.
TextStyle.FULL , // How long or abbreviated.
Locale.US // Or Locale.CANADA_FRENCH or so on.
) // Returns `String` such as `Monday` or `lundi`.
For Java 6 & 7, see the ThreeTen-Backportproject. For earlier Android, see the ThreeTenABPproject.
对于 Java 6 和 7,请参阅ThreeTen-Backport项目。对于早期的 Android,请参阅ThreeTenABP项目。
回答by PawanSinghla
public static String getDay(int month, int day, int year) {
String res= java.time.format.DateTimeFormatter.ofPattern("EEEE")
.format(java.time.LocalDate.of(year, month, day));
return res; }
must use java.time.LocalDate, if u will use direct LocalDate its show compile time error i.e cannot find symbol, so plz use java.time.
必须使用java.time.LocalDate,如果你将使用直接LocalDate,它的显示编译时错误即找不到符号,所以请使用java.time。
回答by garima garg
You can use new Java8 DateTime API.
您可以使用新的 Java8 DateTime API。
public static String getDay(int day, int month, int year)
{
LocalDate dt=LocalDate.of(year, month, day);
System.out.println("day: " + dt.getDayOfWeek().toString());
return dt.getDayOfWeek().toString();
}
A LocalDate
is a date without time of day, so fine for our purpose. The of
factory method constructs the date that we want. Contrary to the Calendar
class used in the question it numbers the months sanely from 1 for January through 12 for December. A LocalDate
has a getter for day of week. It returns a constant from the DayOfWeek
enum whose toString
method gives us a nice readable string such as MONDAY
, again in contrast to what we get from Calendar
.
ALocalDate
是一个没有时间的日期,这对我们的目的来说很好。该of
工厂方法构造我们想要的日期。与Calendar
问题中使用的类相反,它从一月的 1 到十二月的 12 对月份进行了合理的编号。ALocalDate
有一个星期几的吸气剂。它从DayOfWeek
枚举返回一个常量,其toString
方法为我们提供了一个很好的可读字符串,例如MONDAY
,再次与我们从 中得到的相反Calendar
。
回答by isurie
public static void main(String[] args){
String inputDateStr = String.format("%s/%s/%s", 23, 04, 1995);
Date inputDate = null;
try {
inputDate = new SimpleDateFormat("dd/MM/yyyy").parse(inputDateStr);
} catch (ParseException ex) {
Logger.getLogger(JavaApplication28.class.getName()).log(Level.SEVERE, null, ex);
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(inputDate);
String dayOfWeek = calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.US).toUpperCase();
System.out.println(dayOfWeek);
}