计算某个日期是星期几可以使用Java自带的Calendar类来实现。下面是一些示例代码,演示如何获取某个日期对应的星期。
示例一:获取当前日期所对应的星期
import java.util.Calendar;
public class DateOfWeek {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
int weekday = calendar.get(Calendar.DAY_OF_WEEK);
String weekdayString = getWeekdayString(weekday);
System.out.println("Today is " + weekdayString);
}
/**
* 获取星期的字符串表示
* @param weekday 星期数字表示
* @return 星期的字符串表示
*/
private static String getWeekdayString(int weekday) {
switch (weekday) {
case Calendar.SUNDAY:
return "Sunday";
case Calendar.MONDAY:
return "Monday";
case Calendar.TUESDAY:
return "Tuesday";
case Calendar.WEDNESDAY:
return "Wednesday";
case Calendar.THURSDAY:
return "Thursday";
case Calendar.FRIDAY:
return "Friday";
case Calendar.SATURDAY:
return "Saturday";
default:
throw new IllegalArgumentException("Invalid weekday value: " + weekday);
}
}
}
运行上述程序,输出结果如下:
Today is Friday
示例二:计算某个日期是星期几
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateOfWeek {
public static void main(String[] args) throws Exception {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
Date date = dateFormat.parse("20211111"); // 获取2021年11月11日对应的Date对象
Calendar calendar = Calendar.getInstance();
calendar.setTime(date); // 设置Calendar对象为该日期
int weekday = calendar.get(Calendar.DAY_OF_WEEK);
String weekdayString = getWeekdayString(weekday);
System.out.println("2021-11-11 is " + weekdayString);
}
/**
* 获取星期的字符串表示
* @param weekday 星期数字表示
* @return 星期的字符串表示
*/
private static String getWeekdayString(int weekday) {
switch (weekday) {
case Calendar.SUNDAY:
return "Sunday";
case Calendar.MONDAY:
return "Monday";
case Calendar.TUESDAY:
return "Tuesday";
case Calendar.WEDNESDAY:
return "Wednesday";
case Calendar.THURSDAY:
return "Thursday";
case Calendar.FRIDAY:
return "Friday";
case Calendar.SATURDAY:
return "Saturday";
default:
throw new IllegalArgumentException("Invalid weekday value: " + weekday);
}
}
}
运行上述程序,输出结果如下:
2021-11-11 is Thursday
需要注意的是,在示例二中,我们使用了SimpleDateFormat类将字符串格式化为Date对象,然后再将Date对象转换为Calendar对象,再获取对应的星期。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:利用Java计算某个日期是星期几 - Python技术站