检索给定月份的一周的第一天

时间:2013-03-11 04:08:25

标签: java calendar

鉴于此代码,它将打印出正确的月份和年份,但似乎显示通常不正确的随机日期。我查看了一些链接,包括herehere

import java.util.Calendar;
import javax.swing.JOptionPane;
public class DayOfTheWeek {
  Calendar now = Calendar.getInstance();
  int month;
  int year;
  String[] monthString;
  public String monthOfInspection() {
    String Month = JOptionPane.showInputDialog("Select month of inspection: ");
    month = Integer.parseInt(Month);
    monthString = new String[] {
      "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"
    };
    return monthString[month - 1];
  }
  public int yearOfInspection() {
    if(month == 1) {
      now.get(Calendar.YEAR);
      now.add(Calendar.YEAR, 1);
    }
    year = now.get(Calendar.YEAR);
    return year;
  }
  public void dayOfTheWeek() {
    now.set(Calendar.DAY_OF_MONTH, 1);
    now.set(Calendar.MONTH, month);
    now.set(Calendar.YEAR, year);
    now.set(Calendar.DAY_OF_WEEK_IN_MONTH, 0);
    String[] strDays = new String[] {
      "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
    };
    JOptionPane.showMessageDialog(null, year);
    JOptionPane.showMessageDialog(null, monthString[month - 1]);
    JOptionPane.showMessageDialog(null, now.get(Calendar.DAY_OF_WEEK_IN_MONTH));
    JOptionPane.showMessageDialog(null, strDays[now.get(Calendar.DAY_OF_WEEK_IN_MONTH) - 1]);
  }
}

2 个答案:

答案 0 :(得分:0)

您可能应该使用Calendar.DAY_OF_WEEK代替Calendar.DAY_OF_WEEK_IN_MONTH

public void dayOfTheWeek() {
    now.set(Calendar.YEAR, year);
    now.set(Calendar.MONTH, month);
    now.set(Calendar.DAY_OF_MONTH, 1);

    String[] strDays = new String[] {
      "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
    };
    JOptionPane.showMessageDialog(null, year);
    JOptionPane.showMessageDialog(null, monthString[month - 1]);
    JOptionPane.showMessageDialog(null, now.get(Calendar.DAY_OF_WEEK));
    JOptionPane.showMessageDialog(null, strDays[now.get(Calendar.DAY_OF_WEEK) -     1]);
  }

答案 1 :(得分:0)

假设您有正确的monthyear,这就是您可以做的:

now.set(Calendar.DATE, 1);
now.set(Calendar.MONTH, month);
now.set(Calendar.YEAR, year);
int dayOfWeek = now.get(Calendar.DAY_OF_WEEK);