例如,我有日期:“23/2/2010”(2010年2月23日)。我想把它传递给一个返回星期几的函数。我该怎么做呢?
在这个例子中,函数应该返回String "Tue"。
此外,如果只需要日期顺序,如何检索?
例如,我有日期:“23/2/2010”(2010年2月23日)。我想把它传递给一个返回星期几的函数。我该怎么做呢?
在这个例子中,函数应该返回String "Tue"。
此外,如果只需要日期顺序,如何检索?
当前回答
Calendar cal = Calendar.getInstance(desired date);
cal.setTimeInMillis(System.currentTimeMillis());
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
通过提供当前时间戳获取日值。
其他回答
是的。根据具体情况:
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
对于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。
java.time
使用java。在Java 8及以后版本中内置了时间框架。
DayOfWeek枚举可以生成一个字符串,其中包含自动本地化为本地语言和文化规范的日期名称。指定一个TextStyle来指示您想要长形式或缩写名称。
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.time.format.TextStyle
import java.util.Locale
import java.time.DayOfWeek;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/M/yyyy");
LocalDate date = LocalDate.parse("23/2/2010", formatter); // LocalDate = 2010-02-23
DayOfWeek dow = date.getDayOfWeek(); // Extracts a `DayOfWeek` enum object.
String output = dow.getDisplayName(TextStyle.SHORT, Locale.US); // String = Tue
一句话回答:
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
}
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();
}