例如,我有日期:“23/2/2010”(2010年2月23日)。我想把它传递给一个返回星期几的函数。我该怎么做呢?
在这个例子中,函数应该返回String "Tue"。
此外,如果只需要日期顺序,如何检索?
例如,我有日期:“23/2/2010”(2010年2月23日)。我想把它传递给一个返回星期几的函数。我该怎么做呢?
在这个例子中,函数应该返回String "Tue"。
此外,如果只需要日期顺序,如何检索?
当前回答
我用这个
String[] weekdays = "Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" ");
然后
weekdays[calendar.get(Calendar.DAY_OF_WEEK) - 1]
获取特定的工作日
其他回答
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
您可以尝试以下代码:
import java.time.*;
public class Test{
public static void main(String[] args) {
DayOfWeek dow = LocalDate.of(2010,Month.FEBRUARY,23).getDayOfWeek();
String s = String.valueOf(dow);
System.out.println(String.format("%.3s",s));
}
}
Calendar cal = Calendar.getInstance(desired date);
cal.setTimeInMillis(System.currentTimeMillis());
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
通过提供当前时间戳获取日值。
下面是两行代码片段,使用Java 1.8 Time API满足您的需求。
LocalDate localDate = LocalDate.of(Integer.valueOf(year),Integer.valueOf(month),Integer.valueOf(day));
String dayOfWeek = String.valueOf(localDate.getDayOfWeek());