扫二维码与项目经理沟通
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流
我改造了一下你的代码 :
克拉玛依ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为成都创新互联的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:13518219792(备注:SSL证书合作)期待与您的合作!
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 日历
也是正确
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]);
}
}
/*
题目:输出任意年份任意月份的日历表(公元后)
思路:
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 calendar;
import java.applet.Applet;
import java.awt.*;
import java.util.*;
public class CalendarApplet extends Applet{
private static final long serialVersionUID = 1L;
static final int TOP = 70; //顶端距离
static final int CELLWIDTH=50,CELLHEIGHT = 30; //单元格尺寸
static final int MARGIN = 3; //边界距离
static final int FEBRUARY = 1;
TextField tfYear = new TextField("2004", 5); //显示年份的文本域
Choice monthChoice = new Choice(); //月份选择下拉框
Button btUpdate = new Button("更新"); //更新按钮
GregorianCalendar calendar=new GregorianCalendar(); //日历对象
Font smallFont = new Font("TimesRoman", Font.PLAIN, 15); //显示小字体
Font bigFont = new Font("TimesRoman", Font.BOLD, 50); //显示大字体
String days[] = {"星期日", "星期一", "星期二", "星期三","星期四", "星期五", "星期六"};
String months[] = {"一月", "二月", "三月", "四月","五月", "六月", "七月", "八月", "九月","十月", "十一月", "十二月"};
int daysInMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; //每个月的天数
int searchMonth,searchYear; //查询的年份及月份
public void init(){
setBackground(Color.white); //设置背景颜色
searchMonth = calendar.get(Calendar.MONTH); //得到系统年份
searchYear = calendar.get(Calendar.YEAR); //得到系统月份
add(new Label(" 年:")); //增加组件到Applet
tfYear.setText(String.valueOf(searchYear)); //设置文本域文字
add(tfYear);
add(new Label(" 月:"));
setSize(360,230);
monthChoice.setFont(smallFont); //设置月份选择下拉框的显示字体
for (int i = 0; i 12; i++) {
monthChoice.add(months[i]); //增加下拉框选项
}
monthChoice.select(searchMonth); //设置下拉框当前选择项
add(monthChoice);
add(btUpdate);
int componentCount=this.getComponentCount(); //得到Applet中的组件数量
for (int i=0;icomponentCount;i++){
getComponent(i).setFont(smallFont); //设置所有组件的显示字体
}
}
public void paint(Graphics g){
FontMetrics fontMetric; //显示字体的FontMetrics对象
int fontAscent;
int dayPos;
int totalWidth, totalHeight; //总的宽度,高度
int numRows; //行数
int xNum, yNum; //水平和垂直方向单元格数量
int numDays;
String dayStr; //显示天数字符串
g.setColor(Color.lightGray); //设置当前颜色
g.setFont(bigFont); //设置当前使用字体
g.drawString(searchYear+"年",60,TOP+70); //绘制字符串
g.drawString((searchMonth+1)+"月",200,TOP+130);
g.setColor(Color.black);
g.setFont(smallFont);
fontMetric = g.getFontMetrics(); //获取变量初值
fontAscent = fontMetric.getAscent();
dayPos = TOP + fontAscent / 2;
totalWidth = 7 * CELLWIDTH; //得到总的表格宽度
for (int i = 0; i 7; i++) {
g.drawString(days[i], (CELLWIDTH-fontMetric.stringWidth(days[i]))/2 + i*CELLWIDTH,dayPos-20); //绘制表格标题栏
}
numRows = getNumberRows(searchYear, searchMonth); //计算需要的行的数量
totalHeight = numRows * CELLHEIGHT; //得到总的表格高度
for (int i = 0; i = totalWidth; i += CELLWIDTH) {
g.drawLine(i, TOP , i, TOP+ totalHeight); //绘制表格线
}
for (int i = 0, j = TOP ; i = numRows; i++, j += CELLHEIGHT) {
g.drawLine(0, j, totalWidth, j); //绘制表格线
}
xNum = (getFirstDayOfMonth(searchYear, searchMonth) + 1) * CELLWIDTH - MARGIN;
yNum = TOP + MARGIN + fontAscent;
numDays = daysInMonth[searchMonth] + ((calendar.isLeapYear(searchYear) (searchMonth == FEBRUARY)) ? 1 : 0);
for (int day = 1; day = numDays; day++) {
dayStr = Integer.toString(day);
g.drawString(dayStr, xNum - fontMetric.stringWidth(dayStr), yNum); //绘制字符串
xNum += CELLWIDTH;
if (xNum totalWidth) {
xNum = CELLWIDTH - MARGIN;
yNum += CELLHEIGHT;
}
}
}
public boolean action(Event e, Object o){
int searchYearInt;
if (e.target==btUpdate){
searchMonth = monthChoice.getSelectedIndex(); //得到查询月份
searchYearInt = Integer.parseInt(tfYear.getText(), 10); //得到查询年份
if (searchYearInt 1581) {
searchYear = searchYearInt;
}
repaint(); //重绘屏幕
return true;
}
return false;
}
private int getNumberRows(int year, int month) { //得到行数量
int firstDay;
int numCells;
if (year 1582) { //年份小于1582年,则返回-1
return (-1);
}
if ((month 0) || (month 11)) {
return (-1);
}
firstDay = getFirstDayOfMonth(year, month); //计算月份的第一天
if ((month == FEBRUARY) (firstDay == 0) !calendar.isLeapYear(year)) {
return 4;
}
numCells = firstDay + daysInMonth[month];
if ((month == FEBRUARY) (calendar.isLeapYear(year))) {
numCells++;
}
return ((numCells = 35) ? 5 : 6); //返回行数
}
private int getFirstDayOfMonth(int year, int month) { //得到每月的第一天
int firstDay;
int i;
if (year 1582) { //年份小于1582年,返回-1
return (-1);
}
if ((month 0) || (month 11)) { //月份数错误,返回-1
return (-1);
}
firstDay = getFirstDayOfYear(year); //得到每年的第一天
for (i = 0; i month; i++) {
firstDay += daysInMonth[i]; //计算每月的第一天
}
if ((month FEBRUARY) calendar.isLeapYear(year)) {
firstDay++;
}
return (firstDay % 7);
}
private int getFirstDayOfYear(int year){ //计算每年的第一天
int leapYears;
int hundreds;
int fourHundreds;
int first;
if (year 1582) { //如果年份小于1582年
return (-1); //返回-1
}
leapYears = (year - 1581) / 4;
hundreds = (year - 1501) / 100;
leapYears -= hundreds;
fourHundreds = (year - 1201) / 400;
leapYears += fourHundreds;
first=5 + (year - 1582) + leapYears % 7; //得到每年第一天
return first;
}
}
/*
* DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
* dateFormat.format(new Date());//1987-02-17 21:02:01
*/
我自己弄的,你参考下
按照你的要求编写的Java swing 带界面的万年历代码如下
//日历
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class CCI extends JFrame implements ActionListener{
JButton jb1=new JButton("");
JButton jb2=new JButton("");
JButton jb3=new JButton("");
JButton jb4=new JButton("");
JPanel jp1=new JPanel();
JPanel jp2=new JPanel();
JPanel jp3=new JPanel();
JPanel jp4=new JPanel();
JLabel jl1=new JLabel();
JLabel jl2=new JLabel();
JLabel[]jl=new JLabel[49];
String []week={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
Calendar c=Calendar.getInstance();
int year,month,day;
int nowyear,nowmonth,nowday;
CCI(){
super("简单日历");
nowyear=c.get(Calendar.YEAR);
nowmonth=c.get(Calendar.MONTH)+1;
nowday=c.get(Calendar.DAY_OF_MONTH);
year=nowyear;
month=nowmonth;
day=nowday;
String s=year+"年"+month+"月";
jl1.setForeground(Color.RED);
jl1.setFont(new Font(null,Font.BOLD,20));
jl1.setText(s);
jb1.addActionListener(this);
jb2.addActionListener(this);
jb3.addActionListener(this);
jb4.addActionListener(this);
jp1.add(jb1);jp1.add(jb2);jp1.add(jl1);jp1.add(jb3);jp1.add(jb4);
jp2.setLayout(null);
createMonthPanel();
jp2.add(jp3);
jl2.setFont(new Font(null,Font.BOLD,20));
jl2.setText("今天是"+nowyear+"年"+nowmonth+"月"+nowday+"日");
jp4.add(jl2);
add(jp1,BorderLayout.NORTH);
add(jp2,BorderLayout.CENTER);
add(jp4,BorderLayout.SOUTH);
setSize(500,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource()==jb1){
year=year-1;
String s=year+"年"+month+"月";
jl1.setText(s);
jp3.removeAll();
createMonthPanel();
jp3.validate();
}
if(ae.getSource()==jb2){
if(month==1){
year=year-1;
month=12;
}else{
month=month-1;
}
String s=year+"年"+month+"月";
jl1.setText(s);
jp3.removeAll();
createMonthPanel();
jp3.validate();
}
if(ae.getSource()==jb3){
if(month==12){
year=year+1;
month=1;
}else{
month=month+1;
}
String s=year+"年"+month+"月";
jl1.setText(s);
jp3.removeAll();
createMonthPanel();
jp3.validate();
}
if(ae.getSource()==jb4){
year=year+1;
String s=year+"年"+month+"月";
jl1.setText(s);
jp3.removeAll();
createMonthPanel();
jp3.validate();
}
}
public static void main(String[] args) {
new CCI();
}
public int getMonthDays(int year, int month) {
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 2:
if ((year%4==0year%100!=0)||year%400==0) {
return 29;
} else {
return 28;
}
default:
return 30;
}
}
public void createMonthPanel(){
c.set(year, month-1, getMonthDays(year,month));
int weekOfMonth=c.get(Calendar.WEEK_OF_MONTH);
if(weekOfMonth==6){
jp3.setLayout(new GridLayout(7,7));
jp3.setBounds(50, 20, 420, 350);
}else{
jp3.setLayout(new GridLayout(6,7));
jp3.setBounds(50, 20, 420, 300);
}
jp3.setBorder(BorderFactory.createEtchedBorder());
for(int i=0;i7;i++){
jl[i]=new JLabel(week[i],JLabel.CENTER);
jl[i].setFont(new Font(null,Font.BOLD,20));
jl[i].setBorder(BorderFactory.createEtchedBorder());
jp3.add(jl[i]);
}
c.set(year, month-1, 1);
int emptyFirst=c.get(Calendar.DAY_OF_WEEK)-1;
int daysOfMonth=getMonthDays(year,month);
for(int i=6+emptyFirst;i=7;i--){
int intyear=year;
int intmonth=month;
if(intmonth==1){
intyear=intyear-1;
intmonth=12;
}else{
intmonth=intmonth-1;
}
int intdays=getMonthDays(intyear,intmonth);
jl[i]=new JLabel((intdays+7-i)+"",JLabel.CENTER);
jl[i].setFont(new Font(null,Font.BOLD,20));
jl[i].setForeground(Color.GRAY);
jl[i].setBorder(BorderFactory.createEtchedBorder());
jp3.add(jl[i]);
}
for(int i=7+emptyFirst;idaysOfMonth+7+emptyFirst;i++){
jl[i]=new JLabel((i-7-emptyFirst+1)+"",JLabel.CENTER);
jl[i].setFont(new Font(null,Font.BOLD,20));
if((i+1)%7==0 || (i+1)%7==1){
jl[i].setForeground(Color.RED);
}else if((i-7-emptyFirst+1)==nowdaymonth==nowmonthyear==nowyear)
jl[i].setForeground(Color.BLUE);
else
jl[i].setForeground(Color.BLACK);
jl[i].setBorder(BorderFactory.createEtchedBorder());
jp3.add(jl[i]);
}
if(weekOfMonth==6)
for(int i=48;i=daysOfMonth+emptyFirst+7;i--){
jl[i]=new JLabel((49-i)+"",JLabel.CENTER);
jl[i].setFont(new Font(null,Font.BOLD,20));
jl[i].setForeground(Color.GRAY);
jl[i].setBorder(BorderFactory.createEtchedBorder());
jp3.add(jl[i]);
}
else
for(int i=41;i=daysOfMonth+emptyFirst+7;i--){
jl[i]=new JLabel((42-i)+"",JLabel.CENTER);
jl[i].setFont(new Font(null,Font.BOLD,20));
jl[i].setForeground(Color.GRAY);
jl[i].setBorder(BorderFactory.createEtchedBorder());
jp3.add(jl[i]);
}
}
}
给你一个现成的,我自己写的。
import java.awt.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
public class WanNianLi extends JFrame implements ActionListener {
private static int year,month,days;
private JButton[] btn=new JButton[days];
WanNianLi() {
super("万年历");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridLayout bl=new GridLayout(5,7);
JPanel pane=new JPanel();
pane.setLayout(bl);
for (int i=0;idays;i++) {
int temp=i+1;
btn[i]=new JButton(""+temp);
btn[i].addActionListener(this);
pane.add(btn[i]);
}
setContentPane(pane);
pack();
setLookAndFeel();
setVisible(true);
}
public static void main(String[] args) {
if (args.length0)
year=Integer.parseInt(args[0]);
else
year=1982;
if (args.length1)
month=Integer.parseInt(args[1]);
else
month=1;
GetDays gd=new GetDays(year,month);
days=gd.getDays();
new WanNianLi();
}
public void actionPerformed(ActionEvent evt) {
Object src=evt.getSource();
for (int i=0;idays;i++)
if (src==btn[i]) {
int day=i+1;
GetWeekday gw=new GetWeekday(year,month,day);
String str="";
switch (gw.getWeekday()) {
case 1:
str="天";
break;
case 2:
str="一";
break;
case 3:
str="二";
break;
case 4:
str="三";
break;
case 5:
str="四";
break;
case 6:
str="五";
break;
case 7:
str="六";
break;
}
setTitle(year+"年"+month+"月"+day+"日"+"星期"+str);
repaint();
}
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.updateComponentTreeUI(this);
}catch(Exception e){
System.out.print(e.toString());
}
}
}
//////////////
//获取星期几//
//////////////
class GetWeekday {
private Calendar cal=Calendar.getInstance();
private static int weekday;
public int getWeekday() {
return weekday;
}
GetWeekday(int y,int m,int d) {
cal.clear();
cal.set(Calendar.YEAR,y);
cal.set(Calendar.MONTH,m-1);
cal.set(Calendar.DAY_OF_MONTH,d);
weekday=cal.get(Calendar.DAY_OF_WEEK);
}
}
////////////////////
//获取当前月的天数//
////////////////////
class GetDays {
private static int days;
public int getDays() {
return days;
}
GetDays(int y,int m) {
GregorianCalendar gc=new GregorianCalendar();
switch (m) {
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:
if (gc.isLeapYear(y))
days=29;
else
days=28;
break;
}
}
}
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流