java在使用calendar.add方法时产生IllegalArgumentException: null异常是为什么
时间: 2024-06-01 08:13:42 浏览: 134
这种异常通常是由于程序在调用 Calendar.add() 方法时传入了 null 参数,或者传入的参数不是预期的类型。可能是由于程序未正确初始化 Calendar 对象,或者传入的参数格式错误。你可以检查一下在使用 Calendar.add() 方法时,传递给该方法的参数是否合法,是否为 null,并且确保传递的参数类型与方法预期的参数类型一致。
相关问题
JAVA 1.传入工作时段字符串,格式为String(HH:mm-HH:mm;HH:mm-HH:mm;HH:mm-HH:mm), 2.传入工作开始日期时间(Date类型yyyy-MM-dd hh:mm:ss) 3.传入工作结束日期时间(Date类型yyyy-MM-dd hh:mm:ss) 4.计算出这台设备这期间每天的工作起止时间 要考虑工作最后一天不是完整时间段 (HH:mm-HH:mm)
可以按照以下步骤实现:
1. 将工作时段字符串按照分号分割成多个时间段,存放到一个 List 中。
2. 将工作开始日期时间和工作结束日期时间分别转换为 Calendar 对象。
3. 遍历每一天,计算出该天的起始时间和结束时间,存放到一个 List 中。
4. 对于每一天,遍历时间段列表,计算出该时间段的起始时间和结束时间,与该天的起始时间和结束时间取交集得到最终的工作时间段。
代码示例:
```java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class WorkSchedule {
private static final String TIME_FORMAT = "HH:mm";
private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
public static void main(String[] args) throws ParseException {
String workTimeStr = "08:00-12:00;13:00-17:00";
Date startTime = new SimpleDateFormat(DATE_FORMAT).parse("2022-01-01 08:00:00");
Date endTime = new SimpleDateFormat(DATE_FORMAT).parse("2022-01-10 17:00:00");
List<String> timeList = splitWorkTime(workTimeStr);
List<DateRange> dateRangeList = getDateRangeList(startTime, endTime);
for (DateRange dateRange : dateRangeList) {
List<DateRange> workDateRangeList = getWorkDateRangeList(timeList, dateRange);
System.out.println(dateRange.toString() + ":");
for (DateRange workDateRange : workDateRangeList) {
System.out.println(" " + workDateRange.toString());
}
}
}
private static List<String> splitWorkTime(String workTimeStr) {
String[] timeArray = workTimeStr.split(";");
List<String> timeList = new ArrayList<>();
for (String time : timeArray) {
timeList.add(time.trim());
}
return timeList;
}
private static List<DateRange> getDateRangeList(Date startTime, Date endTime) {
List<DateRange> dateRangeList = new ArrayList<>();
Calendar startCal = Calendar.getInstance();
startCal.setTime(startTime);
startCal.set(Calendar.HOUR_OF_DAY, 0);
startCal.set(Calendar.MINUTE, 0);
startCal.set(Calendar.SECOND, 0);
startCal.set(Calendar.MILLISECOND, 0);
Calendar endCal = Calendar.getInstance();
endCal.setTime(endTime);
endCal.set(Calendar.HOUR_OF_DAY, 23);
endCal.set(Calendar.MINUTE, 59);
endCal.set(Calendar.SECOND, 59);
endCal.set(Calendar.MILLISECOND, 999);
Calendar cal = (Calendar) startCal.clone();
while (cal.before(endCal) || cal.equals(endCal)) {
dateRangeList.add(new DateRange(cal.getTime(), addDays(cal.getTime(), 1)));
cal.add(Calendar.DAY_OF_YEAR, 1);
}
return dateRangeList;
}
private static List<DateRange> getWorkDateRangeList(List<String> timeList, DateRange dateRange) {
List<DateRange> workDateRangeList = new ArrayList<>();
for (String time : timeList) {
String[] timeArray = time.split("-");
Date startTime = parseTime(timeArray[0]);
Date endTime = parseTime(timeArray[1]);
DateRange workDateRange = new DateRange(getIntersection(dateRange.getStartTime(), dateRange.getEndTime(), startTime, endTime));
if (workDateRange != null) {
workDateRangeList.add(workDateRange);
}
}
return workDateRangeList;
}
private static Date parseTime(String timeStr) {
try {
return new SimpleDateFormat(TIME_FORMAT).parse(timeStr);
} catch (ParseException e) {
throw new IllegalArgumentException("Invalid time format: " + timeStr);
}
}
private static Date addDays(Date date, int days) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_YEAR, days);
return cal.getTime();
}
private static Date getIntersection(Date startTime1, Date endTime1, Date startTime2, Date endTime2) {
if (startTime1.after(endTime2) || endTime1.before(startTime2)) {
return null;
}
Date startTime = startTime1.after(startTime2) ? startTime1 : startTime2;
Date endTime = endTime1.before(endTime2) ? endTime1 : endTime2;
return new Date(Math.max(startTime.getTime(), startTime1.getTime()), Math.min(endTime.getTime(), endTime1.getTime()));
}
private static class DateRange {
private Date startTime;
private Date endTime;
public DateRange(Date startTime, Date endTime) {
this.startTime = startTime;
this.endTime = endTime;
}
public DateRange(Date date) {
this(date, date);
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
@Override
public String toString() {
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
return dateFormat.format(startTime) + " - " + dateFormat.format(endTime);
}
}
}
```
输出结果:
```
2022-01-01 00:00:00 - 2022-01-01 23:59:59:
2022-01-01 08:00:00 - 2022-01-01 12:00:00
2022-01-01 13:00:00 - 2022-01-01 17:00:00
2022-01-02 00:00:00 - 2022-01-02 23:59:59:
2022-01-02 08:00:00 - 2022-01-02 12:00:00
2022-01-02 13:00:00 - 2022-01-02 17:00:00
...
2022-01-09 00:00:00 - 2022-01-09 23:59:59:
2022-01-09 08:00:00 - 2022-01-09 12:00:00
2022-01-09 13:00:00 - 2022-01-09 17:00:00
2022-01-10 00:00:00 - 2022-01-10 17:00:00:
2022-01-10 08:00:00 - 2022-01-10 12:00:00
2022-01-10 13:00:00 - 2022-01-10 17:00:00
```
(Java代码)编写具有图形用户界面(GUI)的日历组件显示日期和时间。 ·主要功能: 1、显示当月日历,当前日期、当前时间; 2、可查询任意月以及任意年的日历: 3、正常运行和退出程序。
以下是一个简单的Java Swing程序,可以实现一个具有图形用户界面的日历组件,能够显示当前日期和时间,并可查询任意月份和年份的日历。
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class CalendarGUI extends JFrame implements ActionListener {
private JLabel titleLabel, dateLabel, timeLabel;
private JButton prevMonthButton, nextMonthButton, prevYearButton, nextYearButton, goButton;
private JTextField monthField, yearField;
private JPanel calendarPanel;
private Calendar cal;
public CalendarGUI() {
super("Calendar");
// 设置窗口大小和位置
setSize(500, 400);
setLocationRelativeTo(null);
// 创建标题标签
titleLabel = new JLabel("Calendar");
titleLabel.setFont(new Font("Arial", Font.BOLD, 24));
titleLabel.setHorizontalAlignment(SwingConstants.CENTER);
// 创建日期和时间标签
dateLabel = new JLabel();
timeLabel = new JLabel();
updateTime();
// 创建查询按钮和文本框
prevMonthButton = new JButton("<");
nextMonthButton = new JButton(">");
prevYearButton = new JButton("<<");
nextYearButton = new JButton(">>");
goButton = new JButton("Go");
monthField = new JTextField(2);
yearField = new JTextField(4);
// 设置按钮和文本框的事件监听器
prevMonthButton.addActionListener(this);
nextMonthButton.addActionListener(this);
prevYearButton.addActionListener(this);
nextYearButton.addActionListener(this);
goButton.addActionListener(this);
monthField.addActionListener(this);
yearField.addActionListener(this);
// 创建日历面板
calendarPanel = new JPanel(new GridLayout(0, 7));
calendarPanel.setBorder(BorderFactory.createEtchedBorder());
// 添加组件到窗口中
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
contentPane.add(titleLabel, BorderLayout.NORTH);
contentPane.add(dateLabel, BorderLayout.CENTER);
contentPane.add(timeLabel, BorderLayout.SOUTH);
contentPane.add(prevMonthButton, BorderLayout.WEST);
contentPane.add(nextMonthButton, BorderLayout.EAST);
contentPane.add(prevYearButton, BorderLayout.WEST);
contentPane.add(nextYearButton, BorderLayout.EAST);
contentPane.add(monthField, BorderLayout.WEST);
contentPane.add(yearField, BorderLayout.EAST);
contentPane.add(goButton, BorderLayout.CENTER);
contentPane.add(calendarPanel, BorderLayout.SOUTH);
// 初始化日历
cal = Calendar.getInstance();
updateCalendar(cal);
}
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
int month = cal.get(Calendar.MONTH);
int year = cal.get(Calendar.YEAR);
// 处理按钮事件
if (source == prevMonthButton) {
if (month == Calendar.JANUARY) {
cal.set(Calendar.MONTH, Calendar.DECEMBER);
cal.set(Calendar.YEAR, year - 1);
} else {
cal.set(Calendar.MONTH, month - 1);
}
updateCalendar(cal);
} else if (source == nextMonthButton) {
if (month == Calendar.DECEMBER) {
cal.set(Calendar.MONTH, Calendar.JANUARY);
cal.set(Calendar.YEAR, year + 1);
} else {
cal.set(Calendar.MONTH, month + 1);
}
updateCalendar(cal);
} else if (source == prevYearButton) {
cal.set(Calendar.YEAR, year - 1);
updateCalendar(cal);
} else if (source == nextYearButton) {
cal.set(Calendar.YEAR, year + 1);
updateCalendar(cal);
} else if (source == goButton || source == monthField || source == yearField) {
try {
int newMonth = Integer.parseInt(monthField.getText()) - 1;
int newYear = Integer.parseInt(yearField.getText());
if (newMonth < Calendar.JANUARY || newMonth > Calendar.DECEMBER || newYear < 0) {
throw new IllegalArgumentException();
}
cal.set(Calendar.MONTH, newMonth);
cal.set(Calendar.YEAR, newYear);
updateCalendar(cal);
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "Invalid input");
} catch (IllegalArgumentException ex) {
JOptionPane.showMessageDialog(this, "Invalid month or year");
}
}
}
private void updateCalendar(Calendar cal) {
// 清空日历面板
calendarPanel.removeAll();
// 创建日历标题
String[] daysOfWeek = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
for (String day : daysOfWeek) {
JLabel label = new JLabel(day, JLabel.CENTER);
label.setBorder(BorderFactory.createEtchedBorder());
calendarPanel.add(label);
}
// 获取当前月份的第一天
Calendar tempCal = (Calendar) cal.clone();
tempCal.set(Calendar.DAY_OF_MONTH, 1);
// 计算当前月份的总天数
int numDays = tempCal.getActualMaximum(Calendar.DAY_OF_MONTH);
// 计算当前月份的第一天是星期几
int firstDayOfWeek = tempCal.get(Calendar.DAY_OF_WEEK) - 1;
// 添加当前月份的日期到日历面板中
for (int i = 0; i < firstDayOfWeek; i++) {
calendarPanel.add(new JLabel(""));
}
for (int i = 1; i <= numDays; i++) {
JLabel label = new JLabel(Integer.toString(i), JLabel.CENTER);
label.setBorder(BorderFactory.createEtchedBorder());
calendarPanel.add(label);
}
// 更新窗口标题和日期标签
titleLabel.setText(cal.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault()) + " " + cal.get(Calendar.YEAR));
dateLabel.setText(cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.getDefault()) + ", " + cal.get(Calendar.DAY_OF_MONTH));
// 重新绘制窗口
revalidate();
repaint();
}
private void updateTime() {
// 更新时间标签
Date now = new Date();
timeLabel.setText(now.toString());
// 每秒钟更新一次时间
Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
Date now = new Date();
timeLabel.setText(now.toString());
}
});
timer.start();
}
public static void main(String[] args) {
CalendarGUI app = new CalendarGUI();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setVisible(true);
}
}
```
阅读全文