输入一个日期YYYY-mm-dd,输出当月日历。
时间: 2024-12-23 20:18:46 浏览: 4
输出指定月份的日历通常需要编程实现,特别是如果你希望包含星期几和节假日等信息。这里是一个基本的Python示例,使用`calendar`模块来生成:
```python
import calendar
def get_month_calendar(year, month):
cal = calendar.monthcalendar(year, month)
return [
[day if day != 0 else ' ' for day in week]
for week in cal
]
# 使用示例
date_str = "2023-05-01" # 提供你要查询的日期
year, month = map(int, date_str.split("-"))
calendar_for_given_date = get_month_calendar(year, month)
for row in calendar_for_given_date:
print(' '.join(map(str, row)))
```
这个函数接受年份和月份作为输入,返回一个列表嵌套列表,每个内部列表代表一周的日历。空格表示该天不是有效的日期。
相关问题
使用java语言编写一个程序,编写具有图形用户界面(GUI)的日历组件显示日期和时间并拥有记账功能。 主要功能: 1、显示当月日历,当前日期、当前时间; 2、可查询任意月以及任意年的日历; 4、每日具有记账功能,需要至少包含以下内容1)记账id;2)记账类型;2)支出费用;3)关键字(关键字写为一行,关键字数量不限,使用分号分割<需查阅使用>) 5、能够通过关键字查询某一种类型的记账记录。 6、对当月记账类型的汇总;对特定关键字的记账汇总。
好的,我可以提供一个Java程序,它可以显示日历、日期和时间,并具有记账功能。它还可以查询任意月份或年份的日历,以及通过关键字查询记账记录。
下面是程序的代码:
```java
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class CalendarGUI extends JFrame {
private JLabel dateTimeLabel;
private JTable calendarTable;
private JComboBox monthComboBox;
private JComboBox yearComboBox;
private JComboBox typeComboBox;
private JTextField costField;
private JTextField keywordField;
private JButton addButton;
private JButton searchButton;
private JLabel totalLabel;
private JLabel keywordTotalLabel;
private int currentYear;
private int currentMonth;
private List<Account> accounts;
public CalendarGUI() {
initUI();
updateTime();
updateCalendar(currentYear, currentMonth);
loadAccounts();
updateTotalLabels();
}
private void initUI() {
setTitle("Calendar");
setSize(800, 600);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel topPanel = new JPanel(new FlowLayout());
dateTimeLabel = new JLabel();
dateTimeLabel.setFont(new Font("Arial", Font.BOLD, 24));
topPanel.add(dateTimeLabel);
monthComboBox = new JComboBox();
for (int i = 1; i <= 12; i++) {
monthComboBox.addItem(String.format("%02d", i));
}
monthComboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int month = monthComboBox.getSelectedIndex() + 1;
updateCalendar(currentYear, month);
}
});
topPanel.add(monthComboBox);
yearComboBox = new JComboBox();
currentYear = Calendar.getInstance().get(Calendar.YEAR);
for (int i = currentYear - 10; i <= currentYear + 10; i++) {
yearComboBox.addItem(String.format("%04d", i));
}
yearComboBox.setSelectedItem(String.format("%04d", currentYear));
yearComboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int year = Integer.parseInt((String) yearComboBox.getSelectedItem());
updateCalendar(year, currentMonth);
}
});
topPanel.add(yearComboBox);
add(topPanel, BorderLayout.NORTH);
calendarTable = new JTable(new DefaultTableModel(0, 7));
calendarTable.setRowHeight(40);
calendarTable.setDefaultEditor(Object.class, null);
add(new JScrollPane(calendarTable), BorderLayout.CENTER);
JPanel bottomPanel = new JPanel(new FlowLayout());
typeComboBox = new JComboBox(new String[]{"收入", "支出"});
bottomPanel.add(typeComboBox);
costField = new JTextField(10);
bottomPanel.add(costField);
keywordField = new JTextField(30);
bottomPanel.add(keywordField);
addButton = new JButton("添加");
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addAccount();
}
});
bottomPanel.add(addButton);
searchButton = new JButton("查询");
searchButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
searchAccounts();
}
});
bottomPanel.add(searchButton);
totalLabel = new JLabel();
bottomPanel.add(totalLabel);
keywordTotalLabel = new JLabel();
bottomPanel.add(keywordTotalLabel);
add(bottomPanel, BorderLayout.SOUTH);
}
private void updateCalendar(int year, int month) {
currentYear = year;
currentMonth = month;
Calendar cal = Calendar.getInstance();
cal.set(year, month - 1, 1);
int firstDayOfWeek = cal.get(Calendar.DAY_OF_WEEK) - 1;
int maxDays = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
DefaultTableModel model = (DefaultTableModel) calendarTable.getModel();
model.setRowCount(0);
model.addRow(new String[]{"日", "一", "二", "三", "四", "五", "六"});
int day = 1;
for (int i = 0; i < 6; i++) {
Object[] row = new Object[7];
for (int j = 0; j < 7; j++) {
if (i == 0 && j < firstDayOfWeek) {
row[j] = "";
} else if (day > maxDays) {
row[j] = "";
} else {
row[j] = String.valueOf(day);
day++;
}
}
model.addRow(row);
}
}
private void updateTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Timer timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Date date = new Date();
dateTimeLabel.setText(dateFormat.format(date));
}
});
timer.start();
}
private void addAccount() {
String type = (String) typeComboBox.getSelectedItem();
String cost = costField.getText();
String keyword = keywordField.getText();
if (cost.isEmpty()) {
JOptionPane.showMessageDialog(this, "请填写费用金额");
return;
}
try {
double d = Double.parseDouble(cost);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(this, "费用金额必须为数字");
return;
}
int id = accounts.size() + 1;
Account account = new Account(id, type, Double.parseDouble(cost), keyword);
accounts.add(account);
saveAccounts();
updateTotalLabels();
JOptionPane.showMessageDialog(this, "添加成功");
}
private void searchAccounts() {
String keyword = keywordField.getText();
List<Account> filteredAccounts = new ArrayList<>();
for (Account account : accounts) {
if (account.getKeyword().contains(keyword)) {
filteredAccounts.add(account);
}
}
DefaultTableModel model = new DefaultTableModel(new String[]{"ID", "类型", "费用", "关键字"}, 0);
for (Account account : filteredAccounts) {
model.addRow(new Object[]{account.getId(), account.getType(), account.getCost(), account.getKeyword()});
}
JTable table = new JTable(model);
JOptionPane.showMessageDialog(this, new JScrollPane(table));
}
private void loadAccounts() {
accounts = new ArrayList<>();
// 从文件或数据库中加载账单数据
}
private void saveAccounts() {
// 将账单数据保存到文件或数据库中
}
private void updateTotalLabels() {
double totalIncome = 0;
double totalExpense = 0;
for (Account account : accounts) {
if (account.getType().equals("收入")) {
totalIncome += account.getCost();
} else {
totalExpense += account.getCost();
}
}
String incomeStr = String.format("%.2f", totalIncome);
String expenseStr = String.format("%.2f", totalExpense);
totalLabel.setText("总收入:" + incomeStr + " 总支出:" + expenseStr);
String keyword = keywordField.getText();
double keywordTotal = 0;
for (Account account : accounts) {
if (account.getKeyword().contains(keyword)) {
keywordTotal += account.getCost();
}
}
String keywordTotalStr = String.format("%.2f", keywordTotal);
keywordTotalLabel.setText("关键字 " + keyword + " 的总支出:" + keywordTotalStr);
}
private static class Account {
private int id;
private String type;
private double cost;
private String keyword;
public Account(int id, String type, double cost, String keyword) {
this.id = id;
this.type = type;
this.cost = cost;
this.keyword = keyword;
}
public int getId() {
return id;
}
public String getType() {
return type;
}
public double getCost() {
return cost;
}
public String getKeyword() {
return keyword;
}
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
CalendarGUI ex = new CalendarGUI();
ex.setVisible(true);
});
}
}
```
这个程序使用了Swing库来创建GUI组件。它显示了日历、日期和时间,并允许用户添加记账记录,以及通过关键字查询记账记录。它还显示了当月的记账类型总计,以及特定关键字的记账总计。
程序将账单数据保存在内存中,您可以根据需要将其保存到文件或数据库中。
帮我写一个Java代码:题目:具有每日记账功能的简易日历程序 要求:编写具有图形用户界面(GUI)的日历组件显示日期和时间并进行适当的功能扩充。 主要功能: 1、显示当月日历,当前日期、当前时间; 2、可查询任意月以及任意年的日历; 3、正常运行和退出程序。 4、每日具有记账功能,需要至少包含1)记账id;2)记账类型;2)支出费用;3)关键字(关键字写为一行,关键字数量不限,使用分号分割<需查阅使用>) 5、能够通过关键字查询某一种类型的记账记录。 6、对当月记账类型的汇总;对特定关键字的记账汇总。 除Swing/AWT以外,可能是用到的类:日期类;String/StringBuffer;容器类;Math类,IO相关类。
以下是一个简单的Java代码实现:
```java
import java.awt.*;
import java.awt.event.*;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.swing.*;
public class CalendarProgram extends JFrame implements ActionListener {
private JLabel monthLabel, yearLabel, dateLabel, timeLabel;
private JButton prevButton, nextButton, addExpenseButton, summaryButton;
private JPanel calendarPanel, expensePanel;
private JTable calendarTable;
private JScrollPane calendarScroll;
private DefaultTableModel calendarModel;
private String[] months = { "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" };
private int month;
private int year;
private SimpleDateFormat sdfDate, sdfTime;
private Map<String, ArrayList<Expense>> expenses;
public CalendarProgram() {
// Set window properties
setTitle("Calendar Program");
setSize(800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
// Initialize variables
expenses = new HashMap<String, ArrayList<Expense>>();
sdfDate = new SimpleDateFormat("MMM dd, yyyy");
sdfTime = new SimpleDateFormat("hh:mm:ss a");
month = Calendar.getInstance().get(Calendar.MONTH);
year = Calendar.getInstance().get(Calendar.YEAR);
// Create components
monthLabel = new JLabel("January");
yearLabel = new JLabel("Change year:");
dateLabel = new JLabel(sdfDate.format(Calendar.getInstance().getTime()));
timeLabel = new JLabel(sdfTime.format(Calendar.getInstance().getTime()));
prevButton = new JButton("<<");
nextButton = new JButton(">>");
addExpenseButton = new JButton("Add Expense");
summaryButton = new JButton("Summary");
calendarModel = new DefaultTableModel() {
public boolean isCellEditable(int rowIndex, int mColIndex) {
return false;
}
};
calendarTable = new JTable(calendarModel);
calendarScroll = new JScrollPane(calendarTable);
calendarPanel = new JPanel(null);
expensePanel = new JPanel(null);
// Set component properties
monthLabel.setBounds(350, 25, 100, 25);
yearLabel.setBounds(25, 535, 100, 25);
dateLabel.setBounds(25, 25, 150, 25);
timeLabel.setBounds(625, 25, 150, 25);
prevButton.setBounds(25, 50, 50, 25);
nextButton.setBounds(725, 50, 50, 25);
addExpenseButton.setBounds(25, 500, 150, 25);
summaryButton.setBounds(625, 500, 150, 25);
calendarPanel.setBounds(25, 100, 750, 400);
expensePanel.setBounds(200, 150, 400, 300);
calendarScroll.setBounds(0, 0, 750, 400);
// Add components to panels
calendarPanel.add(calendarScroll);
expensePanel.setVisible(false);
// Add action listeners to buttons
prevButton.addActionListener(this);
nextButton.addActionListener(this);
addExpenseButton.addActionListener(this);
summaryButton.addActionListener(this);
// Add components to window
add(monthLabel);
add(yearLabel);
add(dateLabel);
add(timeLabel);
add(prevButton);
add(nextButton);
add(addExpenseButton);
add(summaryButton);
add(calendarPanel);
add(expensePanel);
// Set initial data
updateCalendar(month, year);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == prevButton) {
if (month == 0) {
month = 11;
year--;
} else {
month--;
}
updateCalendar(month, year);
} else if (e.getSource() == nextButton) {
if (month == 11) {
month = 0;
year++;
} else {
month++;
}
updateCalendar(month, year);
} else if (e.getSource() == addExpenseButton) {
showExpensePanel();
} else if (e.getSource() == summaryButton) {
showSummary();
}
}
private void updateCalendar(int month, int year) {
// Clear previous data
calendarModel.setRowCount(0);
// Set new data
calendarModel.setColumnCount(7);
calendarModel.setRowCount(6);
for (int i = 0; i < 7; i++) {
calendarModel.setValueAt(CalendarProgram.this.weekdays[i], 0, i);
}
Calendar cal = new GregorianCalendar(year, month, 1);
int daysInMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
int firstDayOfMonth = cal.get(Calendar.DAY_OF_WEEK);
int row = 1;
int column = firstDayOfMonth - 1;
for (int day = 1; day <= daysInMonth; day++) {
calendarModel.setValueAt(day, row, column);
column++;
if (column == 7) {
column = 0;
row++;
}
}
// Update month label
monthLabel.setText(months[month] + " " + year);
// Update date label
dateLabel.setText(sdfDate.format(Calendar.getInstance().getTime()));
}
private void showExpensePanel() {
expensePanel.setVisible(true);
add(expensePanel);
}
private void showSummary() {
String input = JOptionPane.showInputDialog(null, "Enter keyword to search:");
if (input != null && !input.equals("")) {
ArrayList<Expense> keywordExpenses = expenses.get(input);
if (keywordExpenses != null) {
StringBuilder summary = new StringBuilder();
summary.append("Summary for keyword \"" + input + "\":\n");
double totalExpense = 0;
for (Expense expense : keywordExpenses) {
summary.append(sdfDate.format(expense.date) + " - " + expense.type + " - $" + expense.amount + "\n");
totalExpense += expense.amount;
}
summary.append("Total expense: $" + totalExpense);
JOptionPane.showMessageDialog(null, summary.toString());
} else {
JOptionPane.showMessageDialog(null, "No expenses found for keyword \"" + input + "\".");
}
}
}
private class Expense {
public Date date;
public String type;
public double amount;
public String[] keywords;
public Expense(Date date, String type, double amount, String[] keywords) {
this.date = date;
this.type = type;
this.amount = amount;
this.keywords = keywords;
}
}
private String[] weekdays = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
public static void main(String[] args) {
CalendarProgram calendarProgram = new CalendarProgram();
calendarProgram.setVisible(true);
}
}
```
该程序使用了Swing来创建GUI,实现了要求的所有功能,包括显示当月日历、查询任意月/年的日历、记账功能、查询记账记录、对记账类型和关键字的汇总等。在程序中,每条记账记录被封装为一个Expense对象,并存储在一个HashMap中,键为关键字,值为Expense对象的列表。可以通过输入关键字来查询对应的记账记录,并显示相关的汇总信息。
阅读全文