日期:2014-05-20  浏览次数:20894 次

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]);
}
}

------解决方案--------------------
如果只是简单的使用 直接查API就行了 下面是自己写的根据日期求星期几类

//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: