例如,我有日期:“23/2/2010”(2010年2月23日)。我想把它传递给一个返回星期几的函数。我该怎么做呢?
在这个例子中,函数应该返回String "Tue"。
此外,如果只需要日期顺序,如何检索?
例如,我有日期:“23/2/2010”(2010年2月23日)。我想把它传递给一个返回星期几的函数。我该怎么做呢?
在这个例子中,函数应该返回String "Tue"。
此外,如果只需要日期顺序,如何检索?
当前回答
有一个关于hackerrank Java日期和时间的挑战
就我个人而言,我更喜欢LocalDate类。
进口java.time.LocalDate 使用“of”方法检索localDate,该方法包含3个参数 “int”格式。 最后,使用“getDayOfWeek”方法获取当天的名称。
有一个关于这个挑战的视频。
Java日期和时间Hackerrank解决方案
我希望它会有所帮助:)
其他回答
对于Java 8或更高版本,Localdate更可取
import java.time.LocalDate;
public static String findDay(int month, int day, int year) {
LocalDate localDate = LocalDate.of(year, month, day);
java.time.DayOfWeek dayOfWeek = localDate.getDayOfWeek();
System.out.println(dayOfWeek);
return dayOfWeek.toString();
}
注意:如果输入是字符串/用户定义的,那么你应该把它解析成int。
private String getDay(Date date){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE");
//System.out.println("DAY "+simpleDateFormat.format(date).toUpperCase());
return simpleDateFormat.format(date).toUpperCase();
}
private String getDay(String dateStr){
//dateStr must be in DD-MM-YYYY Formate
Date date = null;
String day=null;
try {
date = new SimpleDateFormat("DD-MM-YYYY").parse(dateStr);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE");
//System.out.println("DAY "+simpleDateFormat.format(date).toUpperCase());
day = simpleDateFormat.format(date).toUpperCase();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return day;
}
是的。根据具体情况:
You can use java.util.Calendar: Calendar c = Calendar.getInstance(); c.setTime(yourDate); int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); if you need the output to be Tue rather than 3 (Days of week are indexed starting at 1 for Sunday, see Calendar.SUNDAY), instead of going through a calendar, just reformat the string: new SimpleDateFormat("EE").format(date) (EE meaning "day of week, short version") if you have your input as string, rather than Date, you should use SimpleDateFormat to parse it: new SimpleDateFormat("dd/M/yyyy").parse(dateString) you can use joda-time's DateTime and call dateTime.dayOfWeek() and/or DateTimeFormat. edit: since Java 8 you can now use java.time package instead of joda-time
有一个关于hackerrank Java日期和时间的挑战
就我个人而言,我更喜欢LocalDate类。
进口java.time.LocalDate 使用“of”方法检索localDate,该方法包含3个参数 “int”格式。 最后,使用“getDayOfWeek”方法获取当天的名称。
有一个关于这个挑战的视频。
Java日期和时间Hackerrank解决方案
我希望它会有所帮助:)
为今天找一个日期,然后从中找出一个星期。
LocalDate d = java.time.LocalDate.now();
System.out.println(java.time.LocalDate.now());
Calendar c = Calendar.getInstance();
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
System.out.println(dayOfWeek);