本文目录一览:
- 1、Java中日历类(CalendarClass)的用途?
- 2、Java中解释一些日历类(CalendarClass)中的重要方法?
- 3、如何用JAVA写日历?
- 4、java如何在窗口中显示日历
- 5、java编写日历
- 6、关于java中输出日历
Java中日历类(CalendarClass)的用途?
Java中日历类(Calendar类)的用途如下:
Calendar类的静态方法getInstance()可以初始化一个日历对象:Calendar now = Calendar.getInstance();
可以使用下面三个方法把日历定到任何一个时间:
set(int year ,int month,int date) ;
set(int year ,int month,int date,int hour,int minute) ;
set(int year ,int month,int date,int hour,int minute,int second) ;
如果想获得年份、月份、小时等信息可以使用:
Now.get(Calendar.Month);//这样的方法 0表示一月,1表示二月
get(Calendar.DAY_OF_MONTH);//获得这个月的第几天
get(Calendar.DAY_OF_WEEK);//获得这个星期的第几天
get(Calendar.DAY_OF_YEAR);//获得这个年的第几天
getTimeMillis();//获得当前时间的毫秒表示
1.计算某一月份的最大天数
Calendar time=Calendar.getInstance();
time.clear();
time.set(Calendar.YEAR,year);
time.set(Calendar.MONTH,i-1);//注意,Calendar对象默认一月为0
int day=time.getActualMaximum(Calendar.DAY_OF_MONTH);//本月份的天数
注:在使用set方法之前,必须先clear一下,否则很多信息会继承自系统当前时间
2.Calendar和Date的转化
(1) Calendar转化为Date
Calendar cal=Calendar.getInstance();
Date date=cal.getTime();
(2) Date转化为Calendar
Date date=new Date();
Calendar cal=Calendar.getInstance();
cal.setTime(date);
3.格式化输出日期时间
Date date=new Date();
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
System.out.println(df.format(date));
4.计算相隔天数的方法
public int getDaysBetween (Calendar d1, Calendar d2){
if (d1.after(d2)){ // swap dates so that d1 is start and d2 is end
java.util.Calendar swap = d1;
d1 = d2;
d2 = swap;
}
int days = d2.get(Calendar.DAY_OF_YEAR) - d1.get(Calendar.DAY_OF_YEAR);
int y2 = d2.get(Calendar.YEAR);
if (d1.get(Calendar.YEAR) != y2){
d1 = (Calendar) d1.clone();
do{
days += d1.getActualMaximum(Calendar.DAY_OF_YEAR);//得到当年的实际天数
d1.add(Calendar.YEAR, 1);
} while (d1.get(Calendar.YEAR) != y2);
}
return days;
}
Java中解释一些日历类(CalendarClass)中的重要方法?
Calendar类(理解)
Calendar类是采用手工的方式取得日期,可以通过此类精确到毫秒,此类的定义如下:
public abstract class Calendar extends Object
implements Serializable, Cloneable, ComparableCalendar
这个类本身是一个抽象类,抽象类要想实例化肯定使用子类:GregorianCalendar
package org.lxh.api.datedemo;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class CalendarDemo {
public static void main(String[] args) {
Calendar calendar = new GregorianCalendar();
System.out.println("YEAR: " + calendar.get(Calendar.YEAR));
System.out.println("MONTH: " + (calendar.get(Calendar.MONTH) + 1));
System.out.println("DATE: " + calendar.get(Calendar.DATE));
System.out
.println("HOUR_OF_DAY: " + calendar.get(Calendar.HOUR_OF_DAY));
System.out.println("MINUTE: " + calendar.get(Calendar.MINUTE));
System.out.println("SECOND: " + calendar.get(Calendar.SECOND));
System.out
.println("MILLISECOND: " + calendar.get(Calendar.MILLISECOND));
}
}
但是现在有一个问题,如果每次取时间都按照这种方式取的话,那么得累死,那么能不能设计一个类,可以通过此
类直接取得时间呢,例如:现在给出了如下的一个接口:
package org.lxh.api.datedemo;
public interface DateTime {
/**
*取得日期
* @return 日期的字符串,例如:2009-12-22
*/
public String getDate() ;
/**
*取得日期时间
* @return 日期时间的字符串,例如:2009-12-22 11:06:23.345
*/
public String getDateTime() ;
/**
*取得时间戳
* @return 返回时间戳的字符串,例如:20091222110623345
*/
public String getTimeStamp() ;
}
前面需要补0的问题需要注意,例如:01。
package org.lxh.api.datedemo;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class DateTimeImpl implements DateTime {
private Calendar calendar;
public DateTimeImpl() {
this.calendar = new GregorianCalendar();
}
public String getDate() {
StringBuffer buf = new StringBuffer();
buf.append(calendar.get(Calendar.YEAR)).append("-");
buf.append(this.addZero((calendar.get(Calendar.MONTH) + 1), 2)).append("-");
buf.append(this.addZero(calendar.get(Calendar.DATE), 2));
return buf.toString();
}
public String getDateTime() {
StringBuffer buf = new StringBuffer();
buf.append(calendar.get(Calendar.YEAR)).append("-");
buf.append(this.addZero((calendar.get(Calendar.MONTH) + 1), 2)).append("-");
buf.append(this.addZero(calendar.get(Calendar.DATE), 2)).append(" ");
buf.append(this.addZero(calendar.get(Calendar.HOUR_OF_DAY), 2)).append(":") ;
buf.append(this.addZero(calendar.get(Calendar.MINUTE), 2)).append(":") ;
buf.append(this.addZero(calendar.get(Calendar.SECOND), 2)).append(".") ;
buf.append(this.addZero(calendar.get(Calendar.MILLISECOND), 3)) ;
return buf.toString();
}
@Override
public String getTimeStamp() {
StringBuffer buf = new StringBuffer();
buf.append(calendar.get(Calendar.YEAR));
buf.append(this.addZero((calendar.get(Calendar.MONTH) + 1), 2));
buf.append(this.addZero(calendar.get(Calendar.DATE), 2));
buf.append(this.addZero(calendar.get(Calendar.HOUR_OF_DAY), 2));
buf.append(this.addZero(calendar.get(Calendar.MINUTE), 2)) ;
buf.append(this.addZero(calendar.get(Calendar.SECOND), 2)) ;
buf.append(this.addZero(calendar.get(Calendar.MILLISECOND), 3)) ;
return buf.toString();
}
private String addZero(int num, int len) {
StringBuffer buf = new StringBuffer();
buf.append(num);
while (buf.length() len) {
buf.insert(0, 0);
}
return buf.toString();
}
}
如何用JAVA写日历?
按照你的要求编写的Java日历验证程序如下
UI.java
import java.util.Scanner;
public class UI {
static Scanner sc=new Scanner(System.in);
public static int askInt(String s){
System.out.print(s);
return sc.nextInt();
}
public static void println(String s){
System.out.println(s);
}
}
EE.java
public class EE {
public void validateDateCore(){
int year =UI.askInt("Enter the year: ");
int month=UI.askInt("Enter the month: ");
int day=UI.askInt("Enter the day: ");
if(year 1){
UI.println("The year is not a valid number.");
return;
}
if(month1 || month12){
UI.println("The month is not a valid number.");
return;
}
int monthDay=0;
switch(month){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:monthDay=31;break;
case 4:
case 6:
case 9:
case 11:monthDay=30;break;
case 2:
if((year%4==0 year%100!=0) || year%400==0){
monthDay=29;
}else{
monthDay=28;
}
break;
}
if(day1 || daymonthDay){
UI.println("The day is not a valid number.");
return;
}else{
UI.println("It is "+day+"/"+month+"/"+year+".");
}
}
public static void main(String[] args) {
new EE().validateDateCore();
}
}
运行结果
java如何在窗口中显示日历
MainFrame.java是显示日历程序,Clock.java是日历计算程序(可以不要)。
编译后运行MainFrame这个类即可。
swing窗口显示万年历,jdk1.4以上环境编译运行。
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133 package org.test;import java.awt.BorderLayout;import java.awt.Color;import java.awt.GridLayout;import java.awt.Toolkit;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.sql.Date;import java.util.Calendar;import javax.swing.JComboBox;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;public class MainFrame extends JFrame { private static final long serialVersionUID = -306484324260972141L; JPanel panel = new JPanel(new BorderLayout()); JPanel panel1 = new JPanel(); JPanel panel2 = new JPanel(new GridLayout(7, 7)); JPanel panel3 = new JPanel(); JLabel[] label = new JLabel[49]; JLabel y_label = new JLabel("年份"); JLabel m_label = new JLabel("月份"); JComboBox com1 = new JComboBox(); JComboBox com2 = new JComboBox(); int re_year, re_month, x_size, y_size; String year_num; Calendar now = Calendar.getInstance(); // 实例化Calendar MainFrame() { super("万年历"); setSize(300, 350); x_size = (int) (Toolkit.getDefaultToolkit().getScreenSize().getWidth()); y_size = (int) (Toolkit.getDefaultToolkit().getScreenSize().getHeight()); setLocation((x_size - 300) / 2, (y_size - 350) / 2); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); panel1.add(y_label); panel1.add(com1); panel1.add(m_label); panel1.add(com2); for (int i = 0; i 49; i++) { label[i] = new JLabel("", JLabel.CENTER);// 将显示的字符设置为居中 panel2.add(label[i]); } panel3.add(new Clock(this)); panel.add(panel1, BorderLayout.NORTH); panel.add(panel2, BorderLayout.CENTER); panel.add(panel3, BorderLayout.SOUTH); panel.setBackground(Color.white); panel1.setBackground(Color.white); panel2.setBackground(Color.white); panel3.setBackground(Color.white); Init(); com1.addActionListener(new ClockAction()); com2.addActionListener(new ClockAction()); setContentPane(panel); setVisible(true); setResizable(false); } class ClockAction implements ActionListener { public void actionPerformed(ActionEvent arg0) { int c_year, c_month, c_week; c_year = Integer.parseInt(com1.getSelectedItem().toString()); // 得到当前所选年份 c_month = Integer.parseInt(com2.getSelectedItem().toString()) - 1; // 得到当前月份,并减1,计算机中的月为0-11 c_week = use(c_year, c_month); // 调用函数use,得到星期几 Resetday(c_week, c_year, c_month); // 调用函数Resetday } } public void Init() { int year, month_num, first_day_num; String log[] = { "日", "一", "二", "三", "四", "五", "六" }; for (int i = 0; i 7; i++) { label[i].setText(log[i]); } for (int i = 0; i 49; i = i + 7) { label[i].setForeground(Color.red); // 将星期日的日期设置为红色 } for (int i = 6; i 49; i = i + 7) { label[i].setForeground(Color.green);// 将星期六的日期设置为绿色 } for (int i = 1; i 10000; i++) { com1.addItem("" + i); } for (int i = 1; i 13; i++) { com2.addItem("" + i); } month_num = (int) (now.get(Calendar.MONTH)); // 得到当前时间的月份 year = (int) (now.get(Calendar.YEAR)); // 得到当前时间的年份 com1.setSelectedIndex(year - 1); // 设置下拉列表显示为当前年 com2.setSelectedIndex(month_num); // 设置下拉列表显示为当前月 first_day_num = use(year, month_num); Resetday(first_day_num, year, month_num); } public int use(int reyear, int remonth) { int week_num; now.set(reyear, remonth, 1); // 设置时间为所要查询的年月的第一天 week_num = (int) (now.get(Calendar.DAY_OF_WEEK));// 得到第一天的星期 return week_num; } @SuppressWarnings("deprecation") public void Resetday(int week_log, int year_log, int month_log) { int month_day_score; // 存储月份的天数 int count; month_day_score = 0; count = 1; Date date = new Date(year_log, month_log + 1, 1); // now Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.MONTH, -1); // 前个月 month_day_score = cal.getActualMaximum(Calendar.DAY_OF_MONTH);// 最后一天 for (int i = 7; i 49; i++) { // 初始化标签 label[i].setText(""); } week_log = week_log + 6; // 将星期数加6,使显示正确 month_day_score = month_day_score + week_log; for (int i = week_log; i month_day_score; i++, count++) { label[i].setText(count + ""); } } public static void main(String[] args) { JFrame.setDefaultLookAndFeelDecorated(true); new MainFrame(); }}
12345678910111213141516171819202122232425262728293031323334353637383940414243 package org.test;import java.awt.Color;import java.util.Calendar;import java.awt.Canvas;import java.awt.Font;import java.awt.Graphics;import java.text.SimpleDateFormat;public class Clock extends Canvas implements Runnable{ private static final long serialVersionUID = 3660124045489727166L; MainFrame mf; Thread t; String time; public Clock(MainFrame mf){ this.mf=mf; setSize(280,40); setBackground(Color.white); t=new Thread(this);//实例化线程 t.start(); //调用线程 } public void run(){ while(true){ try{ Thread.sleep(1000);//休眠1秒钟 }catch(InterruptedException e){ System.out.println("异常"); } this.repaint(100); } } public void paint(Graphics g){ Font f=new Font("宋体",Font.BOLD,16); SimpleDateFormat SDF=new SimpleDateFormat("yyyy'年'MM'月'dd'日'HH:mm:ss");//格式化时间显示类型 Calendar now=Calendar.getInstance(); time=SDF.format(now.getTime()); //得到当前日期和时间 g.setFont(f); g.setColor(Color.orange); g.drawString(time,45,25); }}
java编写日历
我给你贴上我在java核心技术中看到的代码吧,当然没有输入年份和月份,是按照当前时间创建的,写有我写的注释,应该能看的懂
/*
* 2012年5月13日10:37:58
* 日历程序
* Function:
* 显示当前月份的日历
* 总结
* 1. 0-11分别代表1-12月
* 1-7分别代表周日-周六
* 2. 使用GregorianCalendar对象的get方法(参数)获取月,日,年等信息
* 3.
*/
import java.text.DateFormatSymbols;
import java.util.*;
public class CalendarTest {
public static void main(String[] args) {
//construct d as current date构造一个日期
GregorianCalendar d = new GregorianCalendar();
//获取今天是这个月的第几天
int today = d.get(Calendar.DAY_OF_MONTH); //Calendar.DAY_OF_MONTH作为参数调用,得到今天是这个月的第几天
int month = d.get(Calendar.MONTH); //月份
d.set(Calendar.DAY_OF_MONTH, 1); //设置d的日期是本月的1号
int weekDay = d.get(Calendar.DAY_OF_WEEK); //获取当天位于本星期的第几天,也就确定了星期几,值的范围是1-7
int firstDayOfWeek = d.getFirstDayOfWeek(); //获取一星期的第一天,我们得到的是Calendar.SUNDAY,因为我们一星期的第一天是周日
int indent = 0; //为了定位本月第一天,定义索引
while (weekDay != firstDayOfWeek) {
//注意,月份用0-11代表1-12月,为了清晰起见,使用常量代替,下面获取月份得到的实际是当前月-1的值,所以我们要加1
//System.out.printf("当前星期的第%d天,位于当月的第%d天, 现在是%d月\n",
// weekDay, d.get(Calendar.DAY_OF_MONTH), d.get(Calendar.MONTH)+1); //Test Code
indent++;//缩进个数+1
d.add(Calendar.DAY_OF_MONTH, -1);//当前天数-1,如果现在是1号,则执行本条代码后,时间变为上一个月最后一天
weekDay = d.get(Calendar.DAY_OF_WEEK); //重新获取当天位于本星期的第几天
}
String[] weekDayNames = new DateFormatSymbols().getShortWeekdays();//获取简短形式的星期字符串数组
//System.out.println(weekDayNames.length);getShortWeekdays()得到的数组的长度是8,下标为0的是没有值1为星期日...7为星期六
//注释代码1
//Java核心技术的代码
/*
do {
//System.out.printf("%4s", weekDayNames[weekDay]); //经过上面定义索引,weekDay代表的是本星期日
d.add(Calendar.DAY_OF_MONTH, 1); //天数加1
weekDay = d.get(Calendar.DAY_OF_WEEK); //重新获得weekDay的值
} while (weekDay != firstDayOfWeek); //当循环完一个星期后,这里判断不成立,退出循环
*/
//我写的代码,替换上面注释代码1
for (int i=1; iweekDayNames.length; i++)//打印星期标题
System.out.printf("%3s\t", weekDayNames[i]);//引号内是一个全角的空格,因为是中文版,不是书上英文环境,中文和空格对于不上,这里我们用\t解决
//System.out.printf("%3s ", weekDayNames[i]); //方式2
System.out.println();//换行
for (int i=1; i=indent; i++)//确定一星期的一天位置,利用上面indent
System.out.printf("\t");//如用方式2,则这里内容是四个全角空格
//实现输出日期
d.set(Calendar.MONTH, month);
d.set(Calendar.DAY_OF_MONTH, 1);
do {
//print day
int day = d.get(Calendar.DAY_OF_MONTH);
System.out.printf("%3d", day);
if (day == today)
System.out.print("*");
System.out.print("\t");
d.add(Calendar.DATE, 1);//天数加1
weekDay = d.get(Calendar.DAY_OF_WEEK);//刷新weekDay
if (weekDay == firstDayOfWeek) //如果这天等于星期天则换行
System.out.println();
} while (d.get(Calendar.MONTH) == month);
}
}
关于java中输出日历
第一句将用户输入的数字设为日历对象的“年”成员变量,第二句和第三句同样,一个是月份,一个是按照每月第一天开始的日期,第四句用于取得一个默认的日历对象。