例如,我有日期:“23/2/2010”(2010年2月23日)。我想把它传递给一个返回星期几的函数。我该怎么做呢?
在这个例子中,函数应该返回String "Tue"。
此外,如果只需要日期顺序,如何检索?
例如,我有日期:“23/2/2010”(2010年2月23日)。我想把它传递给一个返回星期几的函数。我该怎么做呢?
在这个例子中,函数应该返回String "Tue"。
此外,如果只需要日期顺序,如何检索?
当前回答
//to get day of any date
import java.util.Scanner;
import java.util.Calendar;
import java.util.Date;
public class Show {
public static String getDay(String day,String month, String year){
String input_date = month+"/"+day+"/"+year;
Date now = new Date(input_date);
Calendar calendar = Calendar.getInstance();
calendar.setTime(now);
int final_day = (calendar.get(Calendar.DAY_OF_WEEK));
String finalDay[]={"SUNDAY","MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY"};
System.out.println(finalDay[final_day-1]);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String month = in.next();
String day = in.next();
String year = in.next();
getDay(day, month, year);
}
}
其他回答
...
import java.time.LocalDate;
...
//String month = in.next();
int mm = in.nextInt();
//String day = in.next();
int dd = in.nextInt();
//String year = in.next();
int yy = in.nextInt();
in.close();
LocalDate dt = LocalDate.of(yy, mm, dd);
System.out.print(dt.getDayOfWeek());
一句话回答:
return LocalDate.parse("06/02/2018",DateTimeFormatter.ofPattern("dd/MM/yyyy")).getDayOfWeek().name();
使用的例子:
public static String getDayOfWeek(String date){
return LocalDate.parse(date, DateTimeFormatter.ofPattern("dd/MM/yyyy")).getDayOfWeek().name();
}
public static void callerMethod(){
System.out.println(getDayOfWeek("06/02/2018")); //TUESDAY
}
这是正确的…
java.time.LocalDate; //package related to time and date
它提供了内置方法getDayOfWeek()来获取特定星期的日期:
int t;
Scanner s = new Scanner(System.in);
t = s.nextInt();
s.nextLine();
while(t-->0) {
int d, m, y;
String ss = s.nextLine();
String []sss = ss.split(" ");
d=Integer.parseInt(sss[0]);
m = Integer.parseInt(sss[1]);
y = Integer.parseInt(sss[2]);
LocalDate l = LocalDate.of(y, m, d); //method to get the localdate instance
System.out.println(l.getDayOfWeek()); //this returns the enum DayOfWeek
要将枚举l.getDayOfWeek()的值赋给一个字符串,您可能会使用enum中名为name()的方法,该方法返回enum对象的值。
public class TryDateFormats {
public static void main(String[] args) throws ParseException {
String month = "08";
String day = "05";
String year = "2015";
String inputDateStr = String.format("%s/%s/%s", day, month, year);
Date inputDate = new SimpleDateFormat("dd/MM/yyyy").parse(inputDateStr);
Calendar calendar = Calendar.getInstance();
calendar.setTime(inputDate);
String dayOfWeek = calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.US).toUpperCase();
System.out.println(dayOfWeek);
}
}
import java.time.*;
public static String findDay(int month, int day, int year) {
LocalDate localDate = LocalDate.of(year, month, day);
DayOfWeek dayOfWeek = localDate.getDayOfWeek();
return dayOfWeek.name();
}