网站建设资讯

NEWS

网站建设资讯

Java打印日历代码教程 js打印日历

在Java中如何用calendar类输入年和月份打印当月的日历

//日历存放列表

霍尔果斯ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为成都创新互联公司的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:13518219792(备注:SSL证书合作)期待与您的合作!

ListString list = new ArrayListString();

//日期格式

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

//月初

Calendar begin=Calendar.getInstance();

begin.set(Calendar.YEAR, year);

begin.set(Calendar.MONTH, month-1);

begin.set(Calendar.DAY_OF_MONTH,1);

System.out.println(format.format(begin.getTime()));

//月末

Calendar end = Calendar.getInstance();

end.setTime(begin.getTime());

end.add(Calendar.MONTH, 1);

end.add(Calendar.DAY_OF_MONTH,-1);

System.out.println(format.format(end.getTime()));

//创建日历

while(end.compareTo(begin)=0){

list.add(format.format(begin.getTime()));

begin.add(Calendar.DAY_OF_MONTH, 1);

}

//显示日历

for(String date : list){

System.out.println(date);

}

Java日历打印,怎么加输入年份,打印整年12个月打印,输入月份打印季节,下面代码如何优化,给个思路?

建议封装函数,使用数组完成所有的打印

比如获取天数,getDays(int year,int month)

获取星期,getDay(int allDays)

获取极度,getQuater(int month)

然后打印重载写print方法,传入的flag不同打印年 嫉妒等

Java 打印两个月的日历

水平排列有点蛋疼,不过还是想到办法搞定了,希望你运行的时候排列不会有问题。请接招:

import java.text.DateFormat;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Calendar;

import java.util.Date;

import java.util.List;

import java.util.Scanner;

public class CalendarOutput {

private static Calendar cal1, cal2;

private static final String[] DAY_OF_WEEK = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};

private static DateFormat df = new SimpleDateFormat("yyyy年MM月");

private static DateFormat parseDf = new SimpleDateFormat("yyyyMM");

private static Scanner sc;

public static void main(String[] args) {

cal1 = Calendar.getInstance();

cal1.set(Calendar.DATE, 1);

cal1.setFirstDayOfWeek(Calendar.SUNDAY);

cal2 = Calendar.getInstance();

cal2.set(Calendar.DATE, 1);

sc = new Scanner(System.in);

System.out.println("请输入年月(如201411):");

Date d = null;

while(null == d) {

try {

String line = sc.nextLine();

d = parseDf.parse(line);

} catch (ParseException e) {

System.out.println("日期格式不正确,请重新输入!");

d = null;

}

}

cal1.setTime(d);

cal2.set(Calendar.YEAR, cal1.get(Calendar.YEAR));

cal2.set(Calendar.MONTH, cal1.get(Calendar.MONTH));

cal2.add(Calendar.MONTH, 1);

printCal();

}

private static void printCal() {

// 先在最顶部显示年份

System.out.println(String.format("\t%s\t\t\t%s",

df.format(cal1.getTime()), df.format(cal2.getTime())));

printWeek(); // 然后输出星期日到星期一

// 先将两个月的日期保存到两个数组中

String[][] month1 = putMonth(cal1);

String[][] month2 = putMonth(cal2);

// 再将数组中的文字取出来并显示

for(int i = 0; i  month1.length; i ++) {

String[] month = month1[i];

// 逐周输出日期

for(int j = 0; j  month.length; j ++) {

System.out.print(month[j]);

}

// 如果第二个月周数不小于第一个月,则在本行再输出第二个月的日期

System.out.print("\t");

if(month2.length  i) {

for(int j = 0; j  month.length; j ++) {

System.out.print(month2[i][j]);

}

}

System.out.println();

}

// 如果第二个月周数大于第一个月,则再输出第二个月的日期(可用2月份检验)

if(month1.length  month2.length) {

int deltaMonth = month2.length - month1.length;

for(int i = 0; i  deltaMonth; i ++) {

for(int j = 0; j  7; j ++) {

System.out.print("    ");

}

System.out.print("\t");

for(int j = 0; j  7; j ++) {

System.out.print(month2[month1.length + i][j]);

}

}

}

}

private static String[][] putMonth(Calendar cal) {

ListListString listArray = new ArrayListListString();

int month = cal.get(Calendar.MONTH);

cal.set(Calendar.DATE, 1);

int startDayOfWeek1 = cal.get(Calendar.DAY_OF_WEEK);

ListString list = new ArrayListString();

// 先设置为本周属于上个月的几天,以空字符显示

cal.add(Calendar.DATE, -(startDayOfWeek1 - Calendar.SUNDAY) - 1);

for(int i = Calendar.SUNDAY; i  startDayOfWeek1; i ++) {

list.add("\t");

}

// 重新初始化为本月第一天

cal.set(Calendar.MONTH, month);

cal.set(Calendar.DATE, 1);

int maxDate = cal.getActualMaximum(Calendar.DATE); // 本月最多的天数(不用再去判断是否闰年了)

for(int j = 1; j = maxDate; j ++) {

list.add(String.format("%4s", j + ""));

if(list.size() == 7) {

ListString list2 = new ArrayListString(list);

listArray.add(list2); // 碰到星期六就换行

list = new ArrayListString();

} else if(j == maxDate) {

listArray.add(list); // 最后一天就将最后一周添加进来

}

}

String[][] monthDates = new String[listArray.size()][7];

for(int i = 0; i  listArray.size(); i ++) {

ListString item = listArray.get(i);

for(int j = 0; j  7; j ++) {

if(item.size()  j) { // 如果是最后一周的话可能存在下标越界

monthDates[i][j] = item.get(j);

} else { // 下标越界的时候设置为空字符串

monthDates[i][j] = "\t";

}

}

}

return monthDates;

}

private static void printWeek() {

for(int i = Calendar.SUNDAY; i = Calendar.SATURDAY; i ++) {

System.out.print(String.format("%4s", DAY_OF_WEEK[i - 1]));

}

System.out.print("\t");

for(int i = Calendar.SUNDAY; i = Calendar.SATURDAY; i ++) {

System.out.print(String.format("%4s", DAY_OF_WEEK[i - 1]));

}

System.out.println();

}

}

用java控制台实现万年历-要求打印当前年月日的日历表格,要求对当天的日期单独标示

以下是用java swing编写的日历,很好用,在我所做的系统里就能够正常的使用

接下来 是具体代码:

package Demo;

import java.awt.BorderLayout;

import java.awt.Color;

import java.awt.Dimension;

import java.awt.FlowLayout;

import java.awt.Font;

import java.awt.Frame;

import java.awt.GridLayout;

import java.awt.Point;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.MouseAdapter;

import java.awt.event.MouseEvent;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Calendar;

import java.util.Date;

import javax.swing.JButton;

import javax.swing.JDialog;

import javax.swing.JFrame;

import javax.swing.JFormattedTextField;

import javax.swing.JLabel;

import javax.swing.JPanel;

import javax.swing.JSpinner;

import javax.swing.SpinnerNumberModel;

import javax.swing.SwingConstants;

import javax.swing.SwingUtilities;

import javax.swing.border.LineBorder;

import javax.swing.event.ChangeEvent;

import javax.swing.event.ChangeListener;

public class DateChooser extends JPanel implements ActionListener,

ChangeListener {

/**

*

*/

private static final long serialVersionUID = 1L;

int startYear = 1980;

int lastYear = 2050;

int width = 270;

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;

Color rbBorderColor = Color.red;

Color rbButtonColor = Color.pink;

Color rbBtFontColor = Color.red;

JDialog dialog;

JSpinner yearSpin;

JSpinner monthSpin;

JSpinner hourSpin;

JSpinner minuteSpin;

JButton[][] daysButton = new JButton[6][7];

JFormattedTextField jFormattedTextField;

Calendar c = getCalendar();

DateChooser(JFormattedTextField jftf) {

jFormattedTextField = jftf;

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() {

int currentYear = c.get(Calendar.YEAR);

int currentMonth = c.get(Calendar.MONTH) + 1;

int currentHour = c.get(Calendar.HOUR_OF_DAY);

int currentMinute = c.get(Calendar.MINUTE);

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);

minuteSpin = new JSpinner(new SpinnerNumberModel(currentMinute, 0, 59,

1));

minuteSpin.setPreferredSize(new Dimension(35, 20));

minuteSpin.setName("Minute");

minuteSpin.addChangeListener(this);

result.add(minuteSpin);

JLabel minuteLabel = new JLabel("分");

minuteLabel.setForeground(controlTextColor);

result.add(minuteLabel);

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.CENTER);

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.CENTER);

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;

numberButton.addMouseListener(new MouseAdapter() {

public void mouseClicked(MouseEvent e) {

if (e.getClickCount() == 2) {

closeAndSetDate();

}

}

});

result.add(numberButton);

actionCommandId++;

}

return result;

}

private JDialog createDialog(Frame 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;

}

public void showDateChooser(Point position) {

Object tmpobj=SwingUtilities.getWindowAncestor(jFormattedTextField);

if(tmpobj.getClass().isInstance(new JDialog())||tmpobj.getClass().getSuperclass().isInstance(new JDialog()))

{

JDialog ownerdialog = (JDialog) SwingUtilities

.getWindowAncestor(jFormattedTextField);

Frame owner = (Frame) SwingUtilities.getWindowAncestor(ownerdialog);

if (dialog == null || dialog.getOwner() != owner) {

dialog = createDialog(owner);

}

dialog.setLocation(getAppropriateLocation(owner, position));

}

else if(tmpobj.getClass().isInstance(new JFrame())||tmpobj.getClass().getSuperclass().isInstance(new JFrame()))

{

JFrame ownerFrame = (JFrame) SwingUtilities

.getWindowAncestor(jFormattedTextField);

if (dialog == null || dialog.getOwner() != ownerFrame) {

dialog = createDialog(ownerFrame);

}

dialog.setLocation(getAppropriateLocation(ownerFrame, position));

}

flushWeekAndDay();

dialog.setVisible(true);

}

Point getAppropriateLocation(Frame 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;

}

public void closeAndSetDate() {

setDate(c.getTime());

dialog.dispose();

}

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 int getSelectedMinute() {

return ((Integer) minuteSpin.getValue()).intValue();

}

private void dayColorUpdate(boolean isOldDay) {

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() {

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();

if (source.getName().equals("Minute")) {

c.set(Calendar.MINUTE, getSelectedMinute());

return;

}

if (source.getName().equals("Hour")) {

c.set(Calendar.HOUR_OF_DAY, getSelectedHour());

return;

}

dayColorUpdate(true);

if (source.getName().equals("Year")) {

c.set(Calendar.YEAR, getSelectedYear());

}

if (source.getName().equals("Month")) {

c.set(Calendar.MONTH, getSelectedMonth() - 1);

}

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());

c.set(Calendar.DAY_OF_MONTH, newDay);

}

public void setDate(Date date) {

jFormattedTextField.setText(getDefaultDateFormat().format(date));

}

public Date getDate() {

try {

String dateString = jFormattedTextField.getText();

return getDefaultDateFormat().parse(dateString);

} catch (ParseException e) {

return getNowDate();

} catch (Exception ee) {

return getNowDate();

}

}

private static Date getNowDate() {

return Calendar.getInstance().getTime();

}

private static SimpleDateFormat getDefaultDateFormat() {

return new SimpleDateFormat("yyyy-MM-dd HH:mm");

}

}

测试程序:

package Demo;

import java.awt.Point;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.JButton;

import javax.swing.JFormattedTextField;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

public class DemoForDateChooser extends JFrame {

private JFormattedTextField formattedTextField;

/**

* Launch the application

* @param args

*/

public static void main(String args[]) {

try {

DemoForDateChooser frame = new DemoForDateChooser();

frame.setVisible(true);

} catch (Exception e) {

e.printStackTrace();

}

}

/**

* Create the frame

*/

public DemoForDateChooser() {

super();

setTitle("日期选择框");

getContentPane().setLayout(null);

setBounds(100, 100, 383, 137);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

final JPanel panel = new JPanel();

panel.setLayout(null);

panel.setBounds(0, 0, 375, 107);

getContentPane().add(panel);

formattedTextField = new JFormattedTextField();

formattedTextField.setBounds(68, 48, 175, 23);

final JButton button = new JButton();

button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent arg0) {

DateChooser mDateChooser=new DateChooser(formattedTextField);

Point p = button.getLocationOnScreen();

p.y = p.y + 30;

mDateChooser.showDateChooser(p);

formattedTextField.requestFocusInWindow();

}

});

button.setText("选择日期");

button.setBounds(249, 47, 99, 23);

panel.add(button);

final JLabel label = new JLabel();

label.setText("日期:");

label.setBounds(10, 47, 71, 23);

panel.add(label);

panel.add(formattedTextField);

//

}

}


当前文章:Java打印日历代码教程 js打印日历
网页网址:http://cdweb.net/article/hgogod.html