Java判断某天是星期几

题目

我们经常纠结与某天是星期几?请在窗体的文本框中输入一个日期(例如 2019-1220),点击确定按钮,请在标签上显示该天为星期几(例如星期五),如果不是一个合法的日 期,标签上显示“日期不合法”

代码


import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;


public class D3 extends JFrame{
	private JLabel jl;
	private JTextField jf2;
	private JTextField jf;
	private JButton jb;
	public D3()
	{
		jl=new JLabel();
		jf=new JTextField(8);
		jb=new JButton("计算");
		setLayout(new FlowLayout());
		add(jl);
		add(jf);
		add(jb);
		jb.addActionListener(new Listener());
		setSize(400,400);
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new D3();
	}
	private class Listener implements ActionListener
	{

		@Override
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			String str=jf.getText();
			String []a=str.split("-");
			int year=Integer.parseInt(a[0]);
			int month=Integer.parseInt(a[1]);
			int day=Integer.parseInt(a[2]);
			Calendar calendar = Calendar.getInstance();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			try {
				calendar.setTime(sdf.parse(str));
			} catch (ParseException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			int i =calendar.get(Calendar.DAY_OF_WEEK);
			if(year>2020)
			{
				JOptionPane.showMessageDialog(D3.this, "日期不合法");
			}
			else if(month>12||month<1)
			{
				JOptionPane.showMessageDialog(D3.this, "日期不合法");
			}
			else if(year%4==0&&year%100!=0&&month==2&&day>29)
			{
				JOptionPane.showMessageDialog(D3.this, "日期不合法");
			}
			else if(year%4!=0&&month==2&&day>28)
			{
				JOptionPane.showMessageDialog(D3.this, "日期不合法");
			}
			else if((month==1||month==3||month==5||month==7||month==8||month==10||month==12)&&day>31)
			{
				JOptionPane.showMessageDialog(D3.this, "日期不合法");
			}
			else if((month==4||month==6||month==9||month==11)&&day>30)
			{
				JOptionPane.showMessageDialog(D3.this, "日期不合法");
			}
			else 
			{
				if(i == 1){
					JOptionPane.showMessageDialog(D3.this, "今天星期日");
				}
				else{
					if((i-1)==1)
					{
						JOptionPane.showMessageDialog(D3.this, "今天星期一");
					}
					else if((i-1)==2)
					{
						JOptionPane.showMessageDialog(D3.this, "今天星期二");
					}
					else if((i-1)==3)
					{
						JOptionPane.showMessageDialog(D3.this, "今天星期三");
					}
					else if((i-1)==4)
					{
						JOptionPane.showMessageDialog(D3.this, "今天星期四");
					}
					else if((i-1)==5)
					{
						JOptionPane.showMessageDialog(D3.this, "今天星期五");
					}
					else
					{
						JOptionPane.showMessageDialog(D3.this, "今天星期六");
					}
				}

				
			}
		}
		
	}
}

你可能感兴趣的:(Java,Java)