当我通过每个步骤调试初始化日历时,日期正确设置为31.07.2016。但当我跨过日历方法时,日期错误地设置为02.08.2016。任何人都可以解释这种意想不到的行为吗?
import java.util.Calendar;
public class Test {
public static void main(String[] args)
{
Calendar startCalendar = initializeCalendar("31.07.2016");
}
private static Calendar initializeCalendar(String date)
{
int[] dateValues = extractDate(date);
Calendar calendar = createCalendar();
calendar.set(Calendar.DAY_OF_MONTH, dateValues[0]);
calendar.set(Calendar.MONTH, dateValues[1]-1);
calendar.set(Calendar.YEAR, dateValues[2]);
return calendar;
}
private static Calendar createCalendar()
{
Calendar calendar = Calendar.getInstance();
calendar.clear();
return calendar;
}
private static int[] extractDate(String date)
{
String[] ddmmyyy = date.split("\\.");
return new int[]{Integer.parseInt(ddmmyyy[0]), Integer.parseInt(ddmmyyy[1]), Integer.parseInt(ddmmyyy[2])};
}
}
答案 0 :(得分:1)
请不要重新使用ByRef
来代替下一个:
SimpleDateFormat
<强>输出:强>
public static void main(String[] args) throws ParseException {
// Define the corresponding format
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
Calendar startCalendar = Calendar.getInstance();
// Parse "31.07.2016" and set the resulting date to the calendar instance
startCalendar.setTime(format.parse("31.07.2016"));
// Print the formatted date
System.out.println(format.format(startCalendar.getTime()));
}