java根据日期计算星期几
java根据日期计算星期几
[解决办法]
import java.util.*;
class TestDemo
{
public static void main(String[] args)
{
int year = 2012;
int month = 2;
int day = 15;
Calendar calendar = Calendar.getInstance();//获得一个日历
calendar.set(year, month-1, day);//设置当前时间,月份是从0月开始计算
int number = calendar.get(Calendar.DAY_OF_WEEK);//星期表示1-7,是从星期日开始,
String [] str = {"","星期日","星期一","星期二","星期三","星期四","星期五","星期六",};
System.out.println(str[number]);
}
}
//Calculating what date the day the user input, which start with 1st January ,1980(Tuesday).
// 2010-8-28
import java.util.*;
import java.io.*;
import java.text.*;
public class CalculateWeekDay {
private static BufferedReader stdIn =
new BufferedReader(new InputStreamReader(System.in));
private static PrintWriter stdOut =
new PrintWriter(System.out, true);
private static PrintWriter stdErr =
new PrintWriter(System.err, true);
public static void main(String[] args) throws Exception {
/**Date inputDate = new Date();
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd"); //格式化日期
System.out.println(f.format(inputDate));
String str = f.format(inputDate);*/
System.out.print("Please input the date: ");
stdErr.flush();
String str = stdIn.readLine();
String str1[] = str.split("-"); //分隔日期字符串
int year = Integer.parseInt(str1[0]);
int month = Integer.parseInt(str1[1]);
int day = Integer.parseInt(str1[2]);
int total,week,i;
boolean leap = false;
leap = (year%400 == 0)
[解决办法]
(year%100 != 0) & (year%4 == 0); //判断当年是否是瑞年
week = 1; //起始日1979-12-31是monday
total = year - 1980 +(year - 1980 + 3)/4; //计算total的初值
//计算当年前几月的累计天数与total的初值之和
for(i = 1; i <= month - 1; i++) {
switch(i) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
total += 31;
break;
case 4:
case 6:
case 9:
case 11:
total += 30;
break;
case 2:
if(leap)
total += 29;
else
total += 28;
break;
}
}
total = total + day; //将本月天数加上
week = (week + total)%7;
System.out.print("today " + year + "-" + month + "-" +day + " is ");
stdErr.flush();
switch(week) {
case 0:
System.out.println("Sunday");
break;
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuestay");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
}
}
}
import java.util.Calendar;
import java.util.Date;
public class TestWeekDay
{
public static void main(String[] args)
{
Calendar calendar = Calendar.getInstance();
int year = 201;
int month = 10;
int date = 16;
calendar.set(year,month-1,date);
int number = calendar.get(Calendar.DAY_OF_WEEK)-1;
//if(number < 0) number = 0 ;
String[] str = {"星期日","星期一","星期二","星期三","星期四","星期五","星期六",};
System.out.println(str[number]);
}
}