第一句将用户输入的数字设为日历对象的“年”成员变量,第二句和第三句同样,一个是月份,一个是按照每月第一天开始的日期,第四句用于取得一个默认的日历对象。
从策划到设计制作,每一步都追求做到细腻,制作可持续发展的企业网站。为客户提供成都网站设计、做网站、网站策划、网页设计、域名注册、网站空间、网络营销、VI设计、 网站改版、漏洞修补等服务。为客户提供更好的一站式互联网解决方案,以客户的口碑塑造优易品牌,携手广大客户,共同发展进步。
import java.util.Calendar;
import java.util.Scanner;
public class CalendarX {
static Calendar c=Calendar.getInstance();
static String[] wd={"SAT","SUN","MON","TUE","WED","THU","FRI",};
public static void main(String[] args) {
Scanner sn = new Scanner(System.in);
System.out.print("Input year:");
int year=sn.nextInt();
System.out.print("Input month:");
int month=sn.nextInt();
printCalendar(year,month);
}
static void printCalendar(int y,int m){
c.set(Calendar.YEAR, y);
c.set(Calendar.MONTH, m-1);
c.set(Calendar.DATE, 1);
int fd=c.get(Calendar.DAY_OF_WEEK);
int md=c.getActualMaximum(Calendar.DATE);
for(int i=0; i7; i++)System.out.printf("%5s",wd[i]);System.out.println();
for(int i=0; ifd; i++)System.out.printf("%5s","");
for(int i=0; imd; i++){
System.out.printf("%5s",i+1);
if(++fd%7==0)System.out.println();
}
}
}
java获取一个时间的年月日代码及相关解释说明参考下面代码
package zhidao;
import java.util.Calendar;
public class Test {
public static void main(String[] args) {
Calendar cal=Calendar.getInstance();//使用日历类
int year=cal.get(Calendar.YEAR);//获取年份
int month=cal.get(Calendar.MONTH)+1;//获取月份,因为从0开始的,所以要加1
int day=cal.get(Calendar.DAY_OF_MONTH);//获取天
System.out.println("结果:"+year+"-"+month+"-"+day);
}
}
按照你的要求编写的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();
}
}
运行结果
import java.util.Date;
import java.util.Calendar;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.awt.Color;
import java.awt.Font;
import java.awt.Point;
import java.awt.Dimension;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingUtilities;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
import javax.swing.border.LineBorder;
/**
* @company:NEUSOFT
* @Title:日期选择控件
* @Description:在原有基础上修改了以下内容:
* 1. 将容器由Frame改为了Dialog,以便在基于对话框的程序中也能够使用
* 2. 将最小日期由1980改为了1950,考虑到目前球员的出生日期可能早于1980年
* 3. 将初始显示格式设置为 yyyy年MM月dd日 格式,原有的小时去掉了,不适合于出生日期字段
*/
public class DateChooserJButton extends JButton {
private DateChooser dateChooser = null;
private String preLabel = "";
public DateChooserJButton() {
this(getNowDate());
}
public DateChooserJButton(SimpleDateFormat df, String dateString) {
this();
setText(df, dateString);
}
public DateChooserJButton(Date date) {
this("", date);
}
public DateChooserJButton(String preLabel, Date date) {
if (preLabel != null)
this.preLabel = preLabel;
setDate(date);
setBorder(null);
setCursor(new Cursor(Cursor.HAND_CURSOR));
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (dateChooser == null)
dateChooser = new DateChooser();
Point p = getLocationOnScreen();
p.y = p.y + 30;
dateChooser.showDateChooser(p);
}
});
}
private static Date getNowDate() {
return Calendar.getInstance().getTime();
}
private static SimpleDateFormat getDefaultDateFormat() {
return new SimpleDateFormat("yyyy年MM月dd日");
}
// 覆盖父类的方法
public void setText(String s) {
Date date;
try {
date = getDefaultDateFormat().parse(s);
} catch (ParseException e) {
date = getNowDate();
}
setDate(date);
}
public void setText(SimpleDateFormat df, String s) {
Date date;
try {
date = df.parse(s);
} catch (ParseException e) {
date = getNowDate();
}
setDate(date);
}
public void setDate(Date date) {
super.setText(preLabel + getDefaultDateFormat().format(date));
}
public Date getDate() {
String dateString = this.getText().substring(preLabel.length());
try {
return getDefaultDateFormat().parse(dateString);
} catch (ParseException e) {
return getNowDate();
}
}
public String getDateString()
{
Date birth =getDate();
DateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");
return formatDate.format(birth).toString();
//return this.getText().substring(preLabel.length());
}
// 覆盖父类的方法使之无效
//public void addActionListener(ActionListener listener) {
//}
private class DateChooser extends JPanel implements ActionListener,
ChangeListener {
int startYear = 1950; // 默认【最小】显示年份
int lastYear = 2050; // 默认【最大】显示年份
int width = 200; // 界面宽度
int height = 200; // 界面高度
Color backGroundColor = Color.gray; // 底色
// 月历表格配色----------------//
Color palletTableColor = Color.white; // 日历表底色
Color todayBackColor = Color.orange; // 今天背景色
Color weekFontColor = Color.blue; // 星期文字色
Color dateFontColor = Color.black; // 日期文字色
Color weekendFontColor = Color.red; // 周末文字色
// 控制条配色------------------//
Color controlLineColor = Color.pink; // 控制条底色
Color controlTextColor = Color.white; // 控制条标签文字色
Color rbFontColor = Color.white; // RoundBox文字色
Color rbBorderColor = Color.red; // RoundBox边框色
Color rbButtonColor = Color.pink; // RoundBox按钮色
Color rbBtFontColor = Color.red; // RoundBox按钮文字色
JDialog dialog;
JSpinner yearSpin;
JSpinner monthSpin;
JSpinner hourSpin;
JButton[][] daysButton = new JButton[6][7];
DateChooser() {
setLayout(new BorderLayout());
setBorder(new LineBorder(backGroundColor, 2));
setBackground(backGroundColor);
JPanel topYearAndMonth = createYearAndMonthPanal();
add(topYearAndMonth, BorderLayout.NORTH);
JPanel centerWeekAndDay = createWeekAndDayPanal();
add(centerWeekAndDay, BorderLayout.CENTER);
}
private JPanel createYearAndMonthPanal() {
Calendar c = getCalendar();
int currentYear = c.get(Calendar.YEAR);
int currentMonth = c.get(Calendar.MONTH) + 1;
int currentHour = c.get(Calendar.HOUR_OF_DAY);
JPanel result = new JPanel();
result.setLayout(new FlowLayout());
result.setBackground(controlLineColor);
yearSpin = new JSpinner(new SpinnerNumberModel(currentYear,
startYear, lastYear, 1));
yearSpin.setPreferredSize(new Dimension(48, 20));
yearSpin.setName("Year");
yearSpin.setEditor(new JSpinner.NumberEditor(yearSpin, "####"));
yearSpin.addChangeListener(this);
result.add(yearSpin);
JLabel yearLabel = new JLabel("年");
yearLabel.setForeground(controlTextColor);
result.add(yearLabel);
monthSpin = new JSpinner(new SpinnerNumberModel(currentMonth, 1,
12, 1));
monthSpin.setPreferredSize(new Dimension(35, 20));
monthSpin.setName("Month");
monthSpin.addChangeListener(this);
result.add(monthSpin);
JLabel monthLabel = new JLabel("月");
monthLabel.setForeground(controlTextColor);
result.add(monthLabel);
hourSpin = new JSpinner(new SpinnerNumberModel(currentHour, 0, 23,
1));
hourSpin.setPreferredSize(new Dimension(35, 20));
hourSpin.setName("Hour");
hourSpin.addChangeListener(this);
result.add(hourSpin);
JLabel hourLabel = new JLabel("时");
hourLabel.setForeground(controlTextColor);
result.add(hourLabel);
return result;
}
private JPanel createWeekAndDayPanal() {
String colname[] = { "日", "一", "二", "三", "四", "五", "六" };
JPanel result = new JPanel();
// 设置固定字体,以免调用环境改变影响界面美观
result.setFont(new Font("宋体", Font.PLAIN, 12));
result.setLayout(new GridLayout(7, 7));
result.setBackground(Color.white);
JLabel cell;
for (int i = 0; i 7; i++) {
cell = new JLabel(colname[i]);
cell.setHorizontalAlignment(JLabel.RIGHT);
if (i == 0 || i == 6)
cell.setForeground(weekendFontColor);
else
cell.setForeground(weekFontColor);
result.add(cell);
}
int actionCommandId = 0;
for (int i = 0; i 6; i++)
for (int j = 0; j 7; j++) {
JButton numberButton = new JButton();
numberButton.setBorder(null);
numberButton.setHorizontalAlignment(SwingConstants.RIGHT);
numberButton.setActionCommand(String
.valueOf(actionCommandId));
numberButton.addActionListener(this);
numberButton.setBackground(palletTableColor);
numberButton.setForeground(dateFontColor);
if (j == 0 || j == 6)
numberButton.setForeground(weekendFontColor);
else
numberButton.setForeground(dateFontColor);
daysButton[i][j] = numberButton;
result.add(numberButton);
actionCommandId++;
}
return result;
}
private JDialog createDialog(JDialog owner) {
JDialog result = new JDialog(owner, "日期时间选择", true);
result.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
result.getContentPane().add(this, BorderLayout.CENTER);
result.pack();
result.setSize(width, height);
return result;
}
void showDateChooser(Point position) {
JDialog owner = (JDialog) SwingUtilities
.getWindowAncestor(DateChooserJButton.this);
if (dialog == null || dialog.getOwner() != owner)
dialog = createDialog(owner);
dialog.setLocation(getAppropriateLocation(owner, position));
flushWeekAndDay();
dialog.setVisible(true);
}
Point getAppropriateLocation(JDialog owner, Point position) {
Point result = new Point(position);
Point p = owner.getLocation();
int offsetX = (position.x + width) - (p.x + owner.getWidth());
int offsetY = (position.y + height) - (p.y + owner.getHeight());
if (offsetX 0) {
result.x -= offsetX;
}
if (offsetY 0) {
result.y -= offsetY;
}
return result;
}
private Calendar getCalendar() {
Calendar result = Calendar.getInstance();
result.setTime(getDate());
return result;
}
private int getSelectedYear() {
return ((Integer) yearSpin.getValue()).intValue();
}
private int getSelectedMonth() {
return ((Integer) monthSpin.getValue()).intValue();
}
private int getSelectedHour() {
return ((Integer) hourSpin.getValue()).intValue();
}
private void dayColorUpdate(boolean isOldDay) {
Calendar c = getCalendar();
int day = c.get(Calendar.DAY_OF_MONTH);
c.set(Calendar.DAY_OF_MONTH, 1);
int actionCommandId = day - 2 + c.get(Calendar.DAY_OF_WEEK);
int i = actionCommandId / 7;
int j = actionCommandId % 7;
if (isOldDay)
daysButton[i][j].setForeground(dateFontColor);
else
daysButton[i][j].setForeground(todayBackColor);
}
private void flushWeekAndDay() {
Calendar c = getCalendar();
c.set(Calendar.DAY_OF_MONTH, 1);
int maxDayNo = c.getActualMaximum(Calendar.DAY_OF_MONTH);
int dayNo = 2 - c.get(Calendar.DAY_OF_WEEK);
for (int i = 0; i 6; i++) {
for (int j = 0; j 7; j++) {
String s = "";
if (dayNo = 1 dayNo = maxDayNo)
s = String.valueOf(dayNo);
daysButton[i][j].setText(s);
dayNo++;
}
}
dayColorUpdate(false);
}
public void stateChanged(ChangeEvent e) {
JSpinner source = (JSpinner) e.getSource();
Calendar c = getCalendar();
if (source.getName().equals("Hour")) {
c.set(Calendar.HOUR_OF_DAY, getSelectedHour());
setDate(c.getTime());
return;
}
dayColorUpdate(true);
if (source.getName().equals("Year"))
c.set(Calendar.YEAR, getSelectedYear());
else
// (source.getName().equals("Month"))
c.set(Calendar.MONTH, getSelectedMonth() - 1);
setDate(c.getTime());
flushWeekAndDay();
}
public void actionPerformed(ActionEvent e) {
JButton source = (JButton) e.getSource();
if (source.getText().length() == 0)
return;
dayColorUpdate(true);
source.setForeground(todayBackColor);
int newDay = Integer.parseInt(source.getText());
Calendar c = getCalendar();
c.set(Calendar.DAY_OF_MONTH, newDay);
setDate(c.getTime());
}
}
}
这是一个专门的选日期的类 ,你看看完了调用就行了
我给你贴上我在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);
}
}