如何显示一个日历/Java
二、具体代码
1.确定每个月的月历显示
代码如下:
public static int calendar(int first,int month,int year) {
int day = 0;
System.out.print(" "+month);
System.out.println(" 2021");
System.out.printf(" ---------------------------------------------------\n");
System.out.printf("%8s%8s%8s%8s%8s%8s%8s\n","Sun","Mon","Tue","Wed","Thu","Fri","Sat");
if(month ==1||month == 3||month == 5||month==7||month ==8||month == 10||month == 12)
{
day = 31;
}
if(month ==4||month==6||month ==9||month==11)
{
day = 30;
}
if(month ==2)
{
if(year%4==0&&year%100!=0||year%400==0)
{
day = 29;
}
else {
day = 28;
}
}
for(int j = 0;j<first;j++)
{
System.out.print("\t");
}
for(int i = 1;i<=day;i++) {
if((i+first)%7!=0)
{
System.out.printf("%8d",i);
}
else {
System.out.printf("%8d\n",i);
}
}
return 0;
}
2.确定该月处到1月1日的时间距离
代码如下:
public static int Numberofmonth(int year,int month)
{
if(month ==1||month == 3||month == 5||month==7||month ==8||month == 10||month == 12)
{
return 31;
}
if(month ==4||month==6||month ==9||month==11)
{
return 30;
}
if(month ==2)
{
if(year%4==0&&year%100!=0||year%400==0)
{
return 29;
}
else {
return 28;
}
}
return 0;
}
3.全部代码
代码如下:
import java.time.DayOfWeek;
import javax.*;
public class elapsed_time
{
public static void main(String[] args) {
//2021年9月1日到1月1日的距离
//1月1日是星期五
int t = 5;
int year =2021;
int month = 9;
int day = 0;
int d = 0;//月初是星期几
/*
* 如果要计算1800年到现在的情况的话,就是(2021-1800)*12+month
*/
for(int i = 1;i<month;i++)
{
day+=Numberofmonth(2021,i);
}
d = (day+t)%7;
calendar(d, month,2021);
}
public static int Numberofmonth(int year,int month)
{
if(month ==1||month == 3||month == 5||month==7||month ==8||month == 10||month == 12)
{
return 31;
}
if(month ==4||month==6||month ==9||month==11)
{
return 30;
}
if(month ==2)
{
if(year%4==0&&year%100!=0||year%400==0)
{
return 29;
}
else {
return 28;
}
}
return 0;
}
public static int calendar(int first,int month,int year) {
int day = 0;
System.out.print(" "+month);
System.out.println(" 2021");
System.out.printf(" ---------------------------------------------------\n");
System.out.printf("%8s%8s%8s%8s%8s%8s%8s\n","Sun","Mon","Tue","Wed","Thu","Fri","Sat");
if(month ==1||month == 3||month == 5||month==7||month ==8||month == 10||month == 12)
{
day = 31;
}
if(month ==4||month==6||month ==9||month==11)
{
day = 30;
}
if(month ==2)
{
if(year%4==0&&year%100!=0||year%400==0)
{
day = 29;
}
else {
day = 28;
}
}
for(int j = 0;j<first;j++)
{
System.out.print("\t");
}
for(int i = 1;i<=day;i++) {
if((i+first)%7!=0)
{
System.out.printf("%8d",i);
}
else {
System.out.printf("%8d\n",i);
}
}
return 0;
}
}
运行结果
这是我的一个博客,希望以后继续坚持。