在Java中,java.util.Calendar
類是一個抽象基類,它為特定瞬間與一組日歷字段之間的轉(zhuǎn)換提供了一些方法,并為操控這些字段提供了一些方法
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 + " 天");
通過以上示例,你可以學(xué)會如何使用 Calendar
類處理日期格式。請根據(jù)實際需求調(diào)整代碼。