使用Calendar 类 可以实现,
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.util.*;
import javax.swing.*;
public class XingQi extends JFrame {
private JPanel cp;
private JTextField txtTime;
private JTextField txtday;
public static void main(String[] args) {
new XingQi().setVisible(true);
}
public XingQi() {
setTitle("星期几计算器");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 120);
setLocationRelativeTo(null);
cp = new JPanel();
cp.setLayout(new BorderLayout());
setContentPane(cp);
JPanel panelCenter = new JPanel();
panelCenter.setBackground(Color.CYAN);
cp.add(panelCenter, BorderLayout.CENTER);
JLabel txt1 = new JLabel("输入时间:(格式YYYY-MM-DD)");
panelCenter.add(txt1);
txtTime = new JTextField();
panelCenter.add(txtTime);
txtTime.setColumns(10);
JButton okButton = new JButton("计算");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {// 计算出时间
SimpleDateFormat myFmt = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = myFmt.parse(txtTime.getText().trim());
} catch (ParseException e1) {
e1.printStackTrace();
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int w = cal.get(Calendar.DAY_OF_WEEK);
if (w == 1)
txtday.setText("星期天");
if (w == 2)
txtday.setText("星期一");
if (w == 3)
txtday.setText("星期二");
if (w == 4)
txtday.setText("星期三");
if (w == 5)
txtday.setText("星期四");
if (w == 6)
txtday.setText("星期五");
if (w == 7)
txtday.setText("星期六");
}
});
panelCenter.add(okButton);
txtday = new JTextField();
panelCenter.add(txtday);
txtday.setColumns(10);
}
}