没有合适的资源?快使用搜索试试~ 我知道了~
首页Java实现按年月打印日历功能【基于Calendar】
资源详情
资源推荐
Java实现按年月打印日历功能【基于实现按年月打印日历功能【基于Calendar】】
主要介绍了Java实现按年月打印日历功能,涉及java基于Calendar进行日期运算的相关操作技巧,需要的朋友可以
参考下
本文实例讲述了Java实现按年月打印日历功能。分享给大家供大家参考,具体如下:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class CalendarBook {
public static void main(String[] args) throws ParseException {
CalendarBook cb = new CalendarBook();
cb.printWeekTitle();
cb.printCalendar(2018, 3);
}
public void printCalendar(int year, int month) throws ParseException {
String monthStr; // 格式化月份,因为要转成yyyyMMdd格式的
if (month < 10) {
monthStr = "0" + month;
} else {
monthStr = month + ""; // 数字跟字符串拼接转成字符串格式
}
String yearMonthStr = year + monthStr;
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Calendar calendarEnd = Calendar.getInstance();
Calendar calendarStart = Calendar.getInstance();
// 根据年份和月份得到输入月份有多少天
int monthDays = getMonthLastDay(year, month);
// 月初的date字符串
String dateStartStr = yearMonthStr + "01";
// 月末的date字符串
String dateEndStr = yearMonthStr + monthDays;
Date startDate = sdf.parse(dateStartStr);
Date endDate = sdf.parse(dateEndStr);
calendarStart.setTime(startDate);
calendarEnd.setTime(endDate);
// 得到输入月份有多少周
int weeks = calendarEnd.get(Calendar.WEEK_OF_MONTH);
// 得到当月第一天是星期几,这里周日为第一天,从1开始,周一则为2
int dayOfWeek = calendarStart.get(Calendar.DAY_OF_WEEK);
int day = 1;
// 当月的第一周做特殊处理,单独打印一行
for (int i = 1; i <= 7; i++) {
if (i >= dayOfWeek) {
System.out.print(" " + day + " ");
day++;
} else {
System.out.print(" ");
}
}
System.out.println();
// 开始打印从第二周开始的日期
for (int week = 1; week < weeks; week++) {
for (int i = 1; i <= 7; i++) {
if (day > monthDays) {
break;
}
if (day < 10) {
System.out.print(" " + day + " ");
} else {
System.out.print(day + " ");
}
day++;
}
System.out.println();
}
}
public int getMonthLastDay(int year, int month) {
int monthDay;
int[][] day = { { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
{ 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } };
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
// 闰年
monthDay = day[1][month];
} else {
monthDay = day[0][month];
}
weixin_38569722
- 粉丝: 1
- 资源: 925
上传资源 快速赚钱
- 我的内容管理 收起
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
会员权益专享
最新资源
- zigbee-cluster-library-specification
- JSBSim Reference Manual
- c++校园超市商品信息管理系统课程设计说明书(含源代码) (2).pdf
- 建筑供配电系统相关课件.pptx
- 企业管理规章制度及管理模式.doc
- vb打开摄像头.doc
- 云计算-可信计算中认证协议改进方案.pdf
- [详细完整版]单片机编程4.ppt
- c语言常用算法.pdf
- c++经典程序代码大全.pdf
- 单片机数字时钟资料.doc
- 11项目管理前沿1.0.pptx
- 基于ssm的“魅力”繁峙宣传网站的设计与实现论文.doc
- 智慧交通综合解决方案.pptx
- 建筑防潮设计-PowerPointPresentati.pptx
- SPC统计过程控制程序.pptx
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功