在Java中,java.util.Calendar
类是一个抽象基类,它为特定瞬间与一组日历字段之间的转换提供了一些方法,并为操控这些字段提供了一些方法
import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.util.Date;
Calendar
对象:Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 2021);
calendar.set(Calendar.MONTH, 6); // 注意:月份从0开始,所以6表示7月
calendar.set(Calendar.DAY_OF_MONTH, 20);
calendar.set(Calendar.HOUR_OF_DAY, 14);
calendar.set(Calendar.MINUTE, 30);
calendar.set(Calendar.SECOND, 0);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH); // 注意:月份从0开始,所以需要+1
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
Date date = calendar.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
String dateString = "2021-07-20 14:30:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sdf.parse(dateString);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
Calendar calendar1 = Calendar.getInstance();
calendar1.set(2021, 6, 20); // 注意:月份从0开始,所以6表示7月
Calendar calendar2 = Calendar.getInstance();
calendar2.set(2021, 7, 10); // 注意:月份从0开始,所以7表示8月
long millisecondsDiff = Math.abs(calendar1.getTimeInMillis() - calendar2.getTimeInMillis());
long daysDiff = millisecondsDiff / (24 * 60 * 60 * 1000);
System.out.println("两个日期相差 " + daysDiff + " 天");
通过以上示例,你可以学会如何使用 Calendar
类处理日期格式。请根据实际需求调整代码。