在日常編碼中經常需要使用到目前時間以及本月初等相關時間資料,很多時候擷取目前時間都用new Date()方式,用起來極為不友善。下面是通過Calendar類來擷取目前時間的方法:
Date date = Calendar.getInstance().getTime();
SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
String today = simpleFormat.format(date);
其中Calendar.getInstance()方法會建立目前時間的執行個體(類為Calendar)。通過調用getTime()方法,擷取目前時間的date類型
SimpleDateFormat 時間格式的設定,通過在new對象時設定不同的格式,我這裡使用的格式為yyyy-MM-dd,如果要使用其他的格式,則在建立執行個體時,設定不同的格式。
通過調用formate(Date date) 方法,會将參數的時間轉化為目标時間格式。
我的輸出結果為:2014-10-14
同時,Calendar類也能夠擷取一些時間相關的資訊,如:本月第一天、本月最後一天等等。
本月第一天:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH,1);
Date date = calendar.getTime();
SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(simpleFormat.format(date));
本月最後一天:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH,1);
calendar.add(Calendar.MONTH, 1);
calendar.add(Calendar.DAY_OF_MONTH, -1);
Date date = calendar.getTime();
SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(simpleFormat.format(date));