[java] 可视化日历的实现(基于Calendar类 )

时间:2024-05-10 10:05:08

写在前面

博文安排顺序如下

1.写在前面

2.源码

3.思路

4.相关知识

该小程序是对Date类及其相关类的复习

要求如下图:实现可视化日历

[java] 可视化日历的实现(基于Calendar类 )

实现思路

1.先从键盘输入指定格式的字符串(str)
2.将字符串用格式转换类转换成日期( Date date = format.parse(str) )
3.将日期设置成日历类( calendar.setTime(date) )
4.获取当月第一天是周几( calendar.get(Calendar.DAY_OF_WEEK) )
5.获取当月多少天( calendar.getActualMaximum(Calendar.DATE) )
6.按格式输出

源码

 package TestCalendar;

 import java.util.Date;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar; public class visonCalendar {
public static void main(String args[]){ String temp = "2014-11-11";
Calendar calendar = new GregorianCalendar();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); try {
Date date = df.parse(temp);
calendar.setTime(date);
int day = calendar.get(Calendar.DATE);
calendar.set(Calendar.DAY_OF_MONTH, 1);
int FirstDay = calendar.get(Calendar.DAY_OF_WEEK);
int maxDate = calendar.getActualMaximum(Calendar.DATE);
System.out.println(FirstDay); System.out.println("日\t一\t二\t三\t四\t五\t六");
for(int i = 1; i <= maxDate; i++ ){
if (i == day){
System.out.print("*");
}
while((FirstDay-1)>0){ //按照需要打印的格式,本月1号从第FirstDay天开始,所以前面需要(FirstDay-1)个" \t"
System.out.print(" \t");
FirstDay--;
} System.out.print(i+"\t");
int w = calendar.get(Calendar.DAY_OF_WEEK);
if(w == Calendar.SATURDAY){ //每到周六换行
System.out.print("\n");
}
calendar.add(Calendar.DATE, 1); //从1号开始打印,每次打印完日期加1,否则换行if判断无效 }
} catch (ParseException e) {
e.printStackTrace();
} } }

相关知识

Calendar 的 month 从 0 开始,也就是全年 12 个月由 0 ~ 11 进行表示。

Calendar.DAY_OF_WEEK 定义和值如下:

Calendar.SUNDAY = 1
Calendar.MONDAY = 2
Calendar.TUESDAY = 3
Calendar.WEDNESDAY = 4
Calendar.THURSDAY = 5
Calendar.FRIDAY = 6
Calendar.SATURDAY = 7

SimpleDateFormat 的格式定义

Letter Date or Time Component Presentation Examples
G Era designator Text AD
y Year Year 199696
Y Week year Year 200909
M Month in year (context sensitive) Month JulyJul07
L Month in year (standalone form) Month JulyJul07
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
d Day in month Number 10
F Day of week in month Number 2
E Day name in week Text TuesdayTue
u Day number of week (1 = Monday, ..., 7 = Sunday) Number 1
a Am/pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
z Time zone General time zone Pacific Standard TimePSTGMT-08:00
Z Time zone RFC 822 time zone -0800
X Time zone ISO 8601 time zone -08-0800-08:00