Home > Java > JavaBase > body text

Summary of methods to determine the day of the week in java

Release: 2019-12-06 15:29:08
Original
7342 people have browsed it

Summary of methods to determine the day of the week in java

Java method to get the day of the week for a specified date: (Related video tutorial recommendation: java video tutorial)

1. Use the Calendar class

//根据日期取得星期几
	public static String getWeek(Date date){
		String[] weeks = {"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
		if(week_index<0){
			week_index = 0;
		} 
		return weeks[week_index];
	}
Copy after login

The value of the week number member variable SUNDAY-SATURDAY of the Calendar class is 1-7, and the start of the week is Sunday.

2. Use the SimpleDateFormat class

//根据日期取得星期几
public static String getWeek(Date date){ 
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
String week = sdf.format(date);
return week;
}
Copy after login

Note: The format string is case-sensitive

For the parameters passed in when creating SimpleDateFormat: EEEE represents the day of the week, such as "Thursday" ;MMMM represents the Chinese month, such as "November"; MM represents the month, such as "11";

yyyy represents the year, such as "2010"; dd represents the day, such as "25"

For more java related articles, please pay attention to the java basic tutorial column.

The above is the detailed content of Summary of methods to determine the day of the week in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!