簡體   English   中英

檢索給定月份中一周的第一天

[英]Retrieve the first day of the week of a given month

使用此代碼,它將打印出正確的月份和年份,但似乎顯示通常不正確的隨機日期。 我查看了一些鏈接,包括此處此處

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

您可能應該使用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]);
  }

假設您有正確的monthyear ,可以執行以下操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM