import java.text.SimpleDateFormat; import java.util.Calendar; public class TestDate { public static final String[] weeks = { "日", "一", "二", "三", "四", "五", "六" }; public static void main(String[] args) { Calendar c = Calendar.getInstance(); c.set(Calendar.YEAR,2011);//2011年 c.set(Calendar.MONTH,0);//java中Calendar類,月從0開始, 0代表一月 c.set(Calendar.DATE,1);//1號 int day = c.get(Calendar.DAY_OF_WEEK);//獲致是本周的第幾天地, 1代表星期天...7代表星期六 System.out.println(new SimpleDateFormat( "yyyy-MM-dd ").format(c.getTime())); System.out.println("星期" + weeks[day-1]); } } 把以上測試代碼寫作一個方法 方法的參數名為年月日, 即可。當然Calendar 還有很多功能,比如一周的第幾天,一年的第幾個月……
企業建站必須是能夠以充分展現企業形象為主要目的,是企業文化與產品對外擴展宣傳的重要窗口,一個合格的網站不僅僅能為公司帶來巨大的互聯網上的收集和信息發布平臺,創新互聯建站面向各種領域:主動防護網等成都網站設計公司、成都全網營銷推廣解決方案、網站設計等建站排名服務。
以下是用java swing編寫的日歷,很好用,在我所做的系統里就能夠正常的使用
接下來 是具體代碼:
package Demo;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class DateChooser extends JPanel implements ActionListener,
ChangeListener {
/**
*
*/
private static final long serialVersionUID = 1L;
int startYear = 1980;
int lastYear = 2050;
int width = 270;
int height = 200;
Color backGroundColor = Color.gray;
Color palletTableColor = Color.white;
Color todayBackColor = Color.orange;
Color weekFontColor = Color.blue;
Color dateFontColor = Color.black;
Color weekendFontColor = Color.red;
Color controlLineColor = Color.pink;
Color controlTextColor = Color.white;
Color rbFontColor = Color.white;
Color rbBorderColor = Color.red;
Color rbButtonColor = Color.pink;
Color rbBtFontColor = Color.red;
JDialog dialog;
JSpinner yearSpin;
JSpinner monthSpin;
JSpinner hourSpin;
JSpinner minuteSpin;
JButton[][] daysButton = new JButton[6][7];
JFormattedTextField jFormattedTextField;
Calendar c = getCalendar();
DateChooser(JFormattedTextField jftf) {
jFormattedTextField = jftf;
setLayout(new BorderLayout());
setBorder(new LineBorder(backGroundColor, 2));
setBackground(backGroundColor);
JPanel topYearAndMonth = createYearAndMonthPanal();
add(topYearAndMonth, BorderLayout.NORTH);
JPanel centerWeekAndDay = createWeekAndDayPanal();
add(centerWeekAndDay, BorderLayout.CENTER);
}
private JPanel createYearAndMonthPanal() {
int currentYear = c.get(Calendar.YEAR);
int currentMonth = c.get(Calendar.MONTH) + 1;
int currentHour = c.get(Calendar.HOUR_OF_DAY);
int currentMinute = c.get(Calendar.MINUTE);
JPanel result = new JPanel();
result.setLayout(new FlowLayout());
result.setBackground(controlLineColor);
yearSpin = new JSpinner(new SpinnerNumberModel(currentYear, startYear,
lastYear, 1));
yearSpin.setPreferredSize(new Dimension(48, 20));
yearSpin.setName("Year");
yearSpin.setEditor(new JSpinner.NumberEditor(yearSpin, "####"));
yearSpin.addChangeListener(this);
result.add(yearSpin);
JLabel yearLabel = new JLabel("年");
yearLabel.setForeground(controlTextColor);
result.add(yearLabel);
monthSpin = new JSpinner(new SpinnerNumberModel(currentMonth, 1, 12, 1));
monthSpin.setPreferredSize(new Dimension(35, 20));
monthSpin.setName("Month");
monthSpin.addChangeListener(this);
result.add(monthSpin);
JLabel monthLabel = new JLabel("月");
monthLabel.setForeground(controlTextColor);
result.add(monthLabel);
hourSpin = new JSpinner(new SpinnerNumberModel(currentHour, 0, 23, 1));
hourSpin.setPreferredSize(new Dimension(35, 20));
hourSpin.setName("Hour");
hourSpin.addChangeListener(this);
result.add(hourSpin);
JLabel hourLabel = new JLabel("時");
hourLabel.setForeground(controlTextColor);
result.add(hourLabel);
minuteSpin = new JSpinner(new SpinnerNumberModel(currentMinute, 0, 59,
1));
minuteSpin.setPreferredSize(new Dimension(35, 20));
minuteSpin.setName("Minute");
minuteSpin.addChangeListener(this);
result.add(minuteSpin);
JLabel minuteLabel = new JLabel("分");
minuteLabel.setForeground(controlTextColor);
result.add(minuteLabel);
return result;
}
private JPanel createWeekAndDayPanal() {
String colname[] = { "日", "一", "二", "三", "四", "五", "六" };
JPanel result = new JPanel();
result.setFont(new Font("宋體", Font.PLAIN, 12));
result.setLayout(new GridLayout(7, 7));
result.setBackground(Color.white);
JLabel cell;
for (int i = 0; i 7; i++) {
cell = new JLabel(colname[i]);
cell.setHorizontalAlignment(JLabel.CENTER);
if (i == 0 || i == 6)
cell.setForeground(weekendFontColor);
else
cell.setForeground(weekFontColor);
result.add(cell);
}
int actionCommandId = 0;
for (int i = 0; i 6; i++)
for (int j = 0; j 7; j++) {
JButton numberButton = new JButton();
numberButton.setBorder(null);
numberButton.setHorizontalAlignment(SwingConstants.CENTER);
numberButton.setActionCommand(String.valueOf(actionCommandId));
numberButton.addActionListener(this);
numberButton.setBackground(palletTableColor);
numberButton.setForeground(dateFontColor);
if (j == 0 || j == 6)
numberButton.setForeground(weekendFontColor);
else
numberButton.setForeground(dateFontColor);
daysButton[i][j] = numberButton;
numberButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
closeAndSetDate();
}
}
});
result.add(numberButton);
actionCommandId++;
}
return result;
}
private JDialog createDialog(Frame owner) {
JDialog result = new JDialog(owner, "日期時間選擇", true);
result.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
result.getContentPane().add(this, BorderLayout.CENTER);
result.pack();
result.setSize(width, height);
return result;
}
public void showDateChooser(Point position) {
Object tmpobj=SwingUtilities.getWindowAncestor(jFormattedTextField);
if(tmpobj.getClass().isInstance(new JDialog())||tmpobj.getClass().getSuperclass().isInstance(new JDialog()))
{
JDialog ownerdialog = (JDialog) SwingUtilities
.getWindowAncestor(jFormattedTextField);
Frame owner = (Frame) SwingUtilities.getWindowAncestor(ownerdialog);
if (dialog == null || dialog.getOwner() != owner) {
dialog = createDialog(owner);
}
dialog.setLocation(getAppropriateLocation(owner, position));
}
else if(tmpobj.getClass().isInstance(new JFrame())||tmpobj.getClass().getSuperclass().isInstance(new JFrame()))
{
JFrame ownerFrame = (JFrame) SwingUtilities
.getWindowAncestor(jFormattedTextField);
if (dialog == null || dialog.getOwner() != ownerFrame) {
dialog = createDialog(ownerFrame);
}
dialog.setLocation(getAppropriateLocation(ownerFrame, position));
}
flushWeekAndDay();
dialog.setVisible(true);
}
Point getAppropriateLocation(Frame owner, Point position) {
Point result = new Point(position);
Point p = owner.getLocation();
int offsetX = (position.x + width) - (p.x + owner.getWidth());
int offsetY = (position.y + height) - (p.y + owner.getHeight());
if (offsetX 0) {
result.x -= offsetX;
}
if (offsetY 0) {
result.y -= offsetY;
}
return result;
}
public void closeAndSetDate() {
setDate(c.getTime());
dialog.dispose();
}
private Calendar getCalendar() {
Calendar result = Calendar.getInstance();
result.setTime(getDate());
return result;
}
private int getSelectedYear() {
return ((Integer) yearSpin.getValue()).intValue();
}
private int getSelectedMonth() {
return ((Integer) monthSpin.getValue()).intValue();
}
private int getSelectedHour() {
return ((Integer) hourSpin.getValue()).intValue();
}
private int getSelectedMinute() {
return ((Integer) minuteSpin.getValue()).intValue();
}
private void dayColorUpdate(boolean isOldDay) {
int day = c.get(Calendar.DAY_OF_MONTH);
c.set(Calendar.DAY_OF_MONTH, 1);
int actionCommandId = day - 2 + c.get(Calendar.DAY_OF_WEEK);
int i = actionCommandId / 7;
int j = actionCommandId % 7;
if (isOldDay)
daysButton[i][j].setForeground(dateFontColor);
else
daysButton[i][j].setForeground(todayBackColor);
}
private void flushWeekAndDay() {
c.set(Calendar.DAY_OF_MONTH, 1);
int maxDayNo = c.getActualMaximum(Calendar.DAY_OF_MONTH);
int dayNo = 2 - c.get(Calendar.DAY_OF_WEEK);
for (int i = 0; i 6; i++) {
for (int j = 0; j 7; j++) {
String s = "";
if (dayNo = 1 dayNo = maxDayNo)
s = String.valueOf(dayNo);
daysButton[i][j].setText(s);
dayNo++;
}
}
dayColorUpdate(false);
}
public void stateChanged(ChangeEvent e) {
JSpinner source = (JSpinner) e.getSource();
if (source.getName().equals("Minute")) {
c.set(Calendar.MINUTE, getSelectedMinute());
return;
}
if (source.getName().equals("Hour")) {
c.set(Calendar.HOUR_OF_DAY, getSelectedHour());
return;
}
dayColorUpdate(true);
if (source.getName().equals("Year")) {
c.set(Calendar.YEAR, getSelectedYear());
}
if (source.getName().equals("Month")) {
c.set(Calendar.MONTH, getSelectedMonth() - 1);
}
flushWeekAndDay();
}
public void actionPerformed(ActionEvent e) {
JButton source = (JButton) e.getSource();
if (source.getText().length() == 0)
return;
dayColorUpdate(true);
source.setForeground(todayBackColor);
int newDay = Integer.parseInt(source.getText());
c.set(Calendar.DAY_OF_MONTH, newDay);
}
public void setDate(Date date) {
jFormattedTextField.setText(getDefaultDateFormat().format(date));
}
public Date getDate() {
try {
String dateString = jFormattedTextField.getText();
return getDefaultDateFormat().parse(dateString);
} catch (ParseException e) {
return getNowDate();
} catch (Exception ee) {
return getNowDate();
}
}
private static Date getNowDate() {
return Calendar.getInstance().getTime();
}
private static SimpleDateFormat getDefaultDateFormat() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm");
}
}
測試程序:
package Demo;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class DemoForDateChooser extends JFrame {
private JFormattedTextField formattedTextField;
/**
* Launch the application
* @param args
*/
public static void main(String args[]) {
try {
DemoForDateChooser frame = new DemoForDateChooser();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the frame
*/
public DemoForDateChooser() {
super();
setTitle("日期選擇框");
getContentPane().setLayout(null);
setBounds(100, 100, 383, 137);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel panel = new JPanel();
panel.setLayout(null);
panel.setBounds(0, 0, 375, 107);
getContentPane().add(panel);
formattedTextField = new JFormattedTextField();
formattedTextField.setBounds(68, 48, 175, 23);
final JButton button = new JButton();
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
DateChooser mDateChooser=new DateChooser(formattedTextField);
Point p = button.getLocationOnScreen();
p.y = p.y + 30;
mDateChooser.showDateChooser(p);
formattedTextField.requestFocusInWindow();
}
});
button.setText("選擇日期");
button.setBounds(249, 47, 99, 23);
panel.add(button);
final JLabel label = new JLabel();
label.setText("日期:");
label.setBounds(10, 47, 71, 23);
panel.add(label);
panel.add(formattedTextField);
//
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class CalenderTrain extends JFrame implements ActionListener {
JComboBox Month = new JComboBox(); //月份下拉列表框
JComboBox Year = new JComboBox(); //年份下拉列表框
JLabel Year_l = new JLabel("Year::"); //定義標簽
JLabel Month_l = new JLabel("Month::"); //定義標簽
Date now_date = new Date(); //獲取今天的日期
JButton[] button_day = new JButton[49]; //定義一個數組用來存放日期
JButton button_ok = new JButton("Enter"); //現實選擇日期
JButton button_today = new JButton("Today"); //顯示今天按鈕
int now_year = now_date.getYear() + 1900; //獲取年份值
int now_month = now_date.getMonth(); //獲取月份值(當前月份-1)
String year_int = null; //存放年份
int month_int; //存放月份
JPanel pane_ym = new JPanel(); //放置下拉列表框和控制按鈕面板
JPanel pane_day = new JPanel(); //放置日期面板
JPanel pane_parent = new JPanel(); //放置以上兩個面板
//定義方法繪制面板
public CalenderTrain() {
super("Calender!"); //設定面板得title
//---以下幾行使得關閉面板時退出程序
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClose(WindowEvent e) {
System.exit(0);
}
});
//---
setResizable(false); //面板的大小不能變化
//設定年月
/*年份的區間是當前年份的過去10年到當前年份的未來20年
* 月份正常1??12月
*/
for (int i = now_year - 10; i = now_year + 20; i++) {
Year.addItem(i + "");
}
for (int i = 1; i 13; i++) {
Month.addItem(i + "");
}
Year.setSelectedIndex(10);//設定年份下拉列表為當前年份
pane_ym.add(Year_l);//添加年份標簽
pane_ym.add(Year);//添加年份下拉列表框
Month.setSelectedIndex(now_month);//設定月份下拉列表為當前月份
pane_ym.add(Month_l);//添加月份標簽
pane_ym.add(Month);//添加月份下拉列表框
pane_ym.add(button_ok);//添加確定按鈕
pane_ym.add(button_today);//添加“今天”按鈕
button_ok.addActionListener(this);//確定按鈕添加監聽事件
button_today.addActionListener(this);//“今天”按鈕添加監聽事件
//年月設定結束
//初始化日期按鈕并繪制
pane_day.setLayout(new GridLayout(7, 7, 10, 10));
for (int i = 0; i 49; i++) {
button_day[i] = new JButton(" ");
pane_day.add(button_day[i]);
}
this.setDay();//調用setDay()方法
pane_parent.setLayout(new BorderLayout());//設定布局管理器
setContentPane(pane_day);
setContentPane(pane_ym);
pane_parent.add(pane_day, BorderLayout.SOUTH);
pane_parent.add(pane_ym, BorderLayout.NORTH);
setContentPane(pane_parent);
pack();
show();
}
void setDay() {
year_int = Year.getSelectedItem().toString();
month_int = Month.getSelectedIndex();
int year_sel = Integer.parseInt(year_int) - 1900;//獲得年份值
Date dt = new Date(year_sel, month_int, 1);//構造一個日期
GregorianCalendar cal = new GregorianCalendar();//創建一個Calendar實例
cal.setTime(dt);
String week[] = { "Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat" };
int day = 0;//day中存放某個月份的天數
int day_week = 0;//用來存放某個月的第一天是星期幾的數值
//--將星期添加到前7個按鈕中
for (int i = 0; i 7; i++) {
button_day[i].setText(week[i]);
}
//--
/*判斷是幾月份,根據它來設定day的值
* 其中二月份要判斷是否是閏年
*/
if (month_int == 0
|| month_int == 2
|| month_int == 4
|| month_int == 6
|| month_int == 7
|| month_int == 9
|| month_int == 11) {
day = 31;
} else if (
month_int == 3
|| month_int == 5
|| month_int == 8
|| month_int == 10) {
day = 30;
} else {
if (cal.isLeapYear(year_sel)) {
day = 29;
} else {
day = 28;
}
}
day_week = 7 + dt.getDay();
int count = 1;
/*繪制按鈕
* 在這里我們首先要根據選定的月份的第一天是星期幾來確定我們繪制按鈕的起始位置
* 其中day_week就是我們要繪制的起始位置
* 對于那些沒有數值可以顯示的按鈕要置空
*/
for (int i = day_week; i day_week + day; count++, i++) {
if (i % 7 == 0
|| i == 13
|| i == 20
|| i == 27
|| i == 48
|| i == 34
|| i == 41) {
button_day[i].setForeground(Color.RED);
button_day[i].setText(count + "");
} else {
button_day[i].setText(count + "");
}
}
//--對于沒有日期數值顯示的按鈕進行置空處理
if (day_week == 0) {
for (int i = day; i 49; i++) {
button_day[i].setText(" ");
}
} else {
//第一天前面的按鈕置空
for (int i = 7; i day_week; i++) {
button_day[i].setText(" ");
}//最后一天后面的按鈕置空
for (int i = day_week + day; i 49; i++) {
button_day[i].setText(" ");
}
}
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button_ok) {
this.setDay();//如果點擊確定按鈕就調用setDay()重新方法繪制按鈕
} else if (e.getSource() == button_today) {
new CalenderTrain();//如果點擊今天按鈕,得到今天的日期
}
}
public static void main(String[] args) {
CalenderTrain ct = new CalenderTrain();
}
}
我改造了一下你的代碼 :
package?com.mikuma.calendar;
import?java.util.GregorianCalendar;
import?java.util.Scanner;
public?class?Calendar{
public?static?void?main(String[]?args){
int?year?=?0;
int?month?=?0;
Scanner?scanner?=?new?Scanner(System.in);
System.out.println("請輸入您要查詢的年份");
year?=?scanner.nextInt();
System.out.println("請輸入您要查詢的月份");
while?(true){
month?=?scanner.nextInt();
if?(month??0?||?month??12){
System.out.println("月份輸入有誤,請重新輸入");
}else{
break;
}
}
printPermanentCalendar(year,?month);
}
/**
*?輸出萬年歷
*?
*?@param?year
*?@param?month
*/
private?static?void?printPermanentCalendar(int?year,int?month){
int?days?=?0;
int?totaldays?=?0;//獲取1990年至查詢的年份的天數
for?(int?i?=?1900;?i??year;?i++){
totaldays?=?totaldays?+?(isLeapYear(i)???366?:?365);
}
int?beforedays?=?0;//到指定月份的天數
for?(int?i?=?1;?i?=?month;?i++){
switch?(i)?{
case?1:
case?3:
case?5:
case?7:
case?8:
case?10:
case?12:
days?=?31;
break;
case?4:
case?6:
case?9:
case?11:
days?=?30;
break;
case?2:
days?=?isLeapYear(year)???29?:?28;
break;
default:
break;
}
if?(i??month){
beforedays?=?beforedays?+?days;
}
}
totaldays?=?totaldays?+?beforedays;//總計天數,以判斷周幾;
int?weekDay?=?0;
int?temp?=?(1?+?totaldays)?%?7;
if?(temp?==?0){//1990年1月1日星期一,據此日0天星期一,以此類推
weekDay?=?0;
}else{
weekDay?=?temp;
}
System.out.println("星期日\t星期一\t星期二\t星期三\t星期四\t星期五\t星期六");
for?(int?i?=?0;?i??weekDay;?i++){
System.out.print("\t");
}
for?(int?i?=?1;?i?=?days;?i++){
System.out.print(i?+?"\t");
if?((totaldays?+?i)?%?7?==?6){
System.out.print("\n");
}
}
}
private?static?boolean?isLeapYear(int?year){
return?new?GregorianCalendar().isLeapYear(year);
}
}
運行:
對比了下 360日歷:
結果正確
我們再測試下 2017 年 2月
對比 ?360 日歷
也是正確
/*
題目:輸出任意年份任意月份的日歷表(公元后)
思路:
1.已知1年1月1日是星期日,1?%?7?=?1?對應的是星期日,2?%?7?=?2?對應的是星期一,以此類推;
2.計算當年以前所有天數+當年當月1號之前所有天數;
a.年份分平年閏年,平年365天,閏年366天;
b.閏年的判斷方法year?%?400?==?0?||?(year?%?100?!=?0??year?%?4?==?0)若為真,則為閏年否則為平年;
c.定義平年/閏年數組,包含各月天數;
d.遍歷數組求和,計算當年當月前總天數;
e.當年以前所有天數+當年當月前總天數+1即為1年1月1日到當年當月1日的總天數;
3.總天數對7取模,根據結果判斷當月1號是星期幾,輸出空白區域;
4.輸出當月日歷表,逢星期六換行
*/
import?java.util.Scanner;
class?FindMonthList?{
public?static?void?main(String[]?args){
Scanner?sc?=?new?Scanner(System.in);
System.out.println("請輸入年份:");
int?year?=?sc.nextInt();????????????//年份
if?(year??1)?{????????????????????????//判斷非法輸入年份
System.out.println("輸入錯誤!");
return;
}
System.out.println("請輸入月份:");
int?month?=?sc.nextInt();????????????//月份
if?(month??1?||?month??12)?{????????//判斷非法輸入月份
System.out.println("輸入錯誤!");
return;
}
//輸出表頭
System.out.println("-------"?+?year?+?"?年?"?+?month?+?"?月?"?+?"-------");
System.out.println();
System.out.println("日??一??二??三??四??五??六");
//計算當前年份以前所有天數beforeYearTotalDay;每4年一個閏年,閏年366天,平年365天
int?beforeYearTotalDay?=?((year?-?1)?/?4?*?366)?+?(year-1?-?((year?-?1)?/?4))?*?365;
int[]?arrLeapYear?=?{0,31,29,31,30,31,30,31,31,30,31,30,31};????//閏年各月天數????int數組
int[]?arrNormalYear?=?{0,31,28,31,30,31,30,31,31,30,31,30,31};????//平年各月天數????int數組
int?beforeMonthTotalDay?=?0;????????????????????????????????????//定義本年當月之前月份的總天數
if?(year?%?400?==?0?||?(year?%?100?!=?0??year?%?4?==?0))?{????//判斷當前年份是否是閏年
for?(int?i?=?0?;?i??month?;?i?++?)?{????//for循環計算當月之前總天數
//計算當前月份之前的所有天數
beforeMonthTotalDay?=?beforeMonthTotalDay?+?arrLeapYear[i];
}
//判斷當月1日是星期幾
int?totalDay?=?beforeYearTotalDay?+?beforeMonthTotalDay?+?1;
int?week?=?totalDay?%?7;//已知1年1月1日是星期日,即模7得1對應的是星期日
for?(int?i?=?0?;?i??(week?-?1?+?7)?%?7?;?i?++)?{????//如果寫成i??(week-1)會出現i-1的情況
System.out.print("????");//輸出開頭空白
}
for?(int?i?=?1?;i?=?arrLeapYear[month]?;i?++?)?{????//for循環輸出各月天數
System.out.print(i?+?"??");
if?(i??10?)?{????????//小于10的數補一個空格,以便打印整齊
System.out.print("?");
}
if?(i?%?7?==?((7-(week?-?1))?%?7?)?||?i?==?arrLeapYear[month])?{//每逢星期六/尾數換行
System.out.println();
}
}
}?else?{????????//不是閏年就是平年
for?(int?i?=?0?;?i??month?;?i?++?)?{????//for循環計算出當月之前月份總天數
beforeMonthTotalDay?=?beforeMonthTotalDay?+?arrNormalYear[i];
}
//判斷當月1日是星期幾
int?totalDay?=?beforeYearTotalDay?+?beforeMonthTotalDay?+?1;
int?week?=?totalDay?%?7;//已知1年1月1日是星期日,即模7得1對應的是星期日
for?(int?i?=?0?;?i??(week?-?1?+?7)?%?7?;?i?++)?{????//如果寫成i??(week-1)會出現i-1的情況
System.out.print("????");//輸出開頭空白
}
for?(int?i?=?1?;i?=?arrNormalYear[month]?;i?++?)?{//for循環輸出各月天數
System.out.print(i?+?"??");
if?(i??10?)?{????????????//小于10的數補一個空格,以便打印整齊
System.out.print("?");
}
if?(i?%?7?==?((7-(week?-?1))?%?7?)?||?i?==?arrNormalYear[month])?{//每逢星期六/尾數換行
System.out.println();
}
}
}
}
}
顯示效果:
package org.java.test;
import java.util.Scanner;
public class CalendarTest{
public static void main(String[] args) {
System.out.println("歡 迎 使 用 萬 年 歷");
Scanner input = new Scanner(System.in);
System.out.print("\n請選擇年份: ");
int year = input.nextInt();
System.out.print("\n請選擇月份: ");
int month = input.nextInt();
System.out.println();
int days = 0; // 存儲當月的天數
boolean isRn;
/* 判斷是否是閏年 */
if (year % 4 == 0 !(year % 100 == 0) || year % 400 == 0) { // 判斷是否為閏年
isRn = true; // 閏年
} else {
isRn = false;// 平年
}
/* 計算輸入的年份之前的天數 */
int totalDays = 0;
for (int i = 1900; i year; i++) {
/* 判斷閏年或平年,并進行天數累加 */
if (i % 4 == 0 !(i % 100 == 0) || i % 400 == 0) { // 判斷是否為閏年
totalDays = totalDays + 366; // 閏年366天
} else {
totalDays = totalDays + 365; // 平年365天
}
}
/* 計算輸入月份之前的天數 */
int beforeDays = 0;
for (int i = 1; i = month; i++) {
switch (i) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days = 31;
break;
case 2:
if (isRn) {
days = 29;
} else {
days = 28;
}
break;
default:
days = 30;
break;
}
if (i month) {
beforeDays = beforeDays + days;
}
}
totalDays = totalDays + beforeDays; // 距離1900年1月1日的天數
/* 計算星期幾 */
int firstDayOfMonth; // 存儲當月第一天是星期幾:星期日為0,星期一~星期六為1~6
int temp = 1 + totalDays % 7; // 從1900年1月1日推算
if (temp == 7) { // 求當月第一天
firstDayOfMonth = 0; // 周日
} else {
firstDayOfMonth = temp;
}
/* 輸出日歷 */
System.out.println("星期日\t星期一\t星期二\t星期三\t星期四\t星期五\t星期六");
for (int nullNo = 0; nullNo firstDayOfMonth; nullNo++) {
System.out.print("\t"); // 輸出空格
}
for (int i = 1; i = days; i++) {
System.out.print(i + "\t");
if ((totalDays + i-1) % 7 == 5) { // 如果當天為周六,輸出換行
System.out.println();
}
}
}
}
這是你要的萬年歷嗎?
標題名稱:java打印萬年歷代碼 java制作萬年歷
分享網址:http://vcdvsql.cn/article2/hiodic.html
成都網站建設公司_創新互聯,為您提供網站維護、移動網站建設、響應式網站、用戶體驗、網站內鏈、外貿網站建設
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯