gpt4 book ai didi

java - 打印日历

转载 作者:行者123 更新时间:2023-12-01 12:16:32 24 4
gpt4 key购买 nike

我知道如何创建像这样的普通日历。

代码:

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;

public class CalendarDateExample {

public static void main(String[] args) {
// Create an instance of a GregorianCalendar
Calendar calendar = new GregorianCalendar(2014, 1, 06);

System.out.println("Year: " + calendar.get(Calendar.YEAR));
System.out.println("Month: " + (calendar.get(Calendar.MONTH) + 1));
System.out.println("Day: " + calendar.get(Calendar.DAY_OF_MONTH));

// Format the output.
SimpleDateFormat date_format = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(date_format.format(calendar.getTime()));
}
}

输出: 年份:2014年 月份:2 天:6 2014-02-06

但是如何显示给定月份和年份的日历,使其看起来像:

July 2005
S M T W Th F S
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31

我是java新手,想知道如何按照上面的方式去做。任何帮助都会很棒!提前致谢

最佳答案

你可以这样做:

Calendar calendar = new GregorianCalendar(2014, 1, 06);
calendar.set(Calendar.DAY_OF_MONTH, 1); //Set the day of month to 1
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); //get day of week for 1st of month
int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

//print month name and year
System.out.println(new SimpleDateFormat("MMMM YYYY").format(calendar.getTime()));
System.out.println(" S M T W T F S");

//print initial spaces
String initialSpace = "";
for (int i = 0; i < dayOfWeek - 1; i++) {
initialSpace += " ";
}
System.out.print(initialSpace);

//print the days of the month starting from 1
for (int i = 0, dayOfMonth = 1; dayOfMonth <= daysInMonth; i++) {
for (int j = ((i == 0) ? dayOfWeek - 1 : 0); j < 7 && (dayOfMonth <= daysInMonth); j++) {
System.out.printf("%2d ", dayOfMonth);
dayOfMonth++;
}
System.out.println();
}

输出:

February 2014
S M T W T F S
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28

关于java - 打印日历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26962388/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com