java简易日历算法

来源:互联网 发布:淘宝双11红包雨 编辑:程序博客网 时间:2024/05/21 06:18

前几天上课的时候,老师出题考了考日历类的使用。当时便突发奇想,便写了这个小东西。。。采用数学取模运算算出各月的工作日(只支持公元前啊委屈

与大家分享一下,若有不足,望各位大牛指正!小弟在这里多谢啦!

贴代码:

import java.math.BigDecimal;
/*以公元前1年1月1日为参照点的运算,公元前1年1月1日为周日!
。。。。。。突然想到圣经里的耶和华创世篇。。。*/
/*只支持公元前的運算!*/
class JudGer {
 private int[] daysList;//所選擇年月份空閒工作時間列表
 private int[] weekday;//所選擇年月份的每日對應的每週周幾列表

 public JudGer() {
  this.daysList = new int[30];
  this.weekday = null;
 }

 public void getDaysList(String time) {
  int count = 0, turns = 0, year = 0, month = 0;
  boolean flag = false;
  String[] times = time.split("-");
  year = new BigDecimal(times[0]).intValue();
  month = new BigDecimal(times[1]).intValue();
  if (year % 4 == 0 || year % 400 == 0)
   flag = true;
  if (month == 2) {
   if (flag == true)
    turns = 29;
   else
    turns = 28;
  } else if (month == 1 || month == 3 || month == 5 || month == 7
    || month == 8 || month == 10 || month == 12)
   turns = 31;
  else
   turns = 30;
  getTheWeekDayList(year, month, turns);
  for (int i = 0; i < turns; i++) {
   if (this.weekday[i] == 6 || this.weekday[i] == 7)
    continue;
   else {
    this.daysList[count] = i + 1;
    count++;
   }
  }
 }

 public void getTheWeekDayList(int y, int m, int turns) {
  int firstweekday = 0, week = 0;
  this.weekday = new int[turns];
  int daysLength = daysLength(y, m);
  if (y >= 1)
   if (daysLength % 7 + 7 > 7)
    firstweekday = daysLength % 7 + 7 - 7;
   else
    firstweekday = daysLength % 7 + 7;
  else if (y < 1)
   System.out.println("error...arguments out of range!");
  for (int i = 0; i < turns; i++) {
   if (week > 7)
    week = 1;
   if (i == 0) {
    this.weekday[i] = (week = firstweekday);
    week++;
   } else
    this.weekday[i] = week++;
  }
 }

 public int daysLength(int y, int m) {
  int yn = 1, day_len = 0;
  for (int i = 1; i <= y; i++)
   if (i % 4 == 0 || i % 400 == 0)
    day_len += 366;
   else
    day_len += 365;
  for (int i = 1; i < m; i++)
   if (i == 1 || i == 3 || i == 5 || i == 7 || i == 8 || i == 10
     || i == 12)
    day_len += 31;
   else if (i == 2)
    if (yn % 4 == 0 || yn % 400 == 0)
     day_len += 29;
    else
     day_len += 28;
   else
    day_len += 30;
  return day_len-1;
 }

 public void printWorkDaysList() {
  for(int i:this.daysList)
   if(i==0)
    return;
   else
    System.out.println("该年该月份工作日为该月"+i+"号");
 }   
}

public class test {
 public static void main(String[] args) {
  JudGer jg = new JudGer();
  jg.getDaysList("2013-7");
  jg.printWorkDaysList();
 }
}

 

原创粉丝点击