Date類和SimpleDate類兩個往往是一起使用的,但是Calendar這個類主要是進(jìn)行一些簡單的日期計算的。
Calendar類定義:
public abstract class Calendar
extends Object
implements Serializable, Cloneable, Comparable<Calendar>
這是一個抽象類,那么應(yīng)該依靠我們的子類,進(jìn)行對象實例化操作。
查看文檔我們知道,構(gòu)造方法被私有化了,(單例模式應(yīng)用),并且一些靜態(tài)常量可以獲取年月日的組成。但是這個類提供一個方法,返回的是本類對象:public static Calendar getInstance()。這樣就能回避掉子類,直接取得實例化對象了。
范例:取得當(dāng)前的日期時間
public class TestDemo{
public static void main(String[] args) throws Exception{
Calendar calendar=Calendar.getInstance();
StringBuffer stringBuffer=new StringBuffer();
stringBuffer.append(calendar.get(Calendar.YEAR)).append("-");
stringBuffer.append(calendar.get(Calendar.MONTH)+1).append("-");//日期Calendar從0開始數(shù)月
stringBuffer.append(calendar.get(Calendar.DAY_OF_MONTH)).append(" ");
stringBuffer.append(calendar.get(Calendar.HOUR_OF_DAY)).append(":");
stringBuffer.append(calendar.get(Calendar.MINUTE)).append(":");
stringBuffer.append(calendar.get(Calendar.SECOND));
System.out.println(stringBuffer);
}
}
結(jié)果:

image.png
但是這個類可以在我們?nèi)〉玫臅r候進(jìn)行一些簡單的計算,例如:若干天之后的日期。
如果是日期計算,要比Date省事,如果使用Date進(jìn)行天的計算,那么就需要使用long完成了。
總結(jié)
1.以后數(shù)據(jù)庫中的日期型就是用java.util.Date表示
2.代碼模型:SimpleDateFormat類實現(xiàn)String與Date間的互相轉(zhuǎn)換。