Date
類 表示特定的瞬間,精確到毫秒。從 JDK 1.1 開始,應該使用Calendar
類實現日期和時間字段之間轉換,使用
DateFormat
類來格式化和解析日期字符串。
DateFormat
:可以自定義時間格式,對時間對象進行操作和解析。實現了時間對象到字符串,和字符串到時間對象的轉換。
Calendar
: 對時間對象(特定瞬間)各個屬性的操作,如對時間的年月日時分秒的獲取,修改,偏移。。
/****
*
* 計算兩個日期相差的天數
*
*/
public static void main(String[] args) throws ParseException {
String s1 = "2014.08.01";
String s2 = "2014.09.03";
//創建日期格式
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd");
//解析字符串生成 Date
Date date1 = simpleDateFormat.parse(s1);
Date date2 = simpleDateFormat.parse(s2);
//獲取相差的毫秒
long time = Math.abs(date1.getTime() - date2.getTime());
//計算相差的天數
int days = (int) (time / 1000 / 60 / 60 / 24);
System.out.println(days);
}
/***********
*一天前的當前時刻 *
*****/
public class DeteDemo {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -1);
showDate(calendar);
}
private static void showDate(Calendar calendar) {
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int date = calendar.get(Calendar.DATE);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
String week = getWeek(calendar.get(Calendar.DAY_OF_WEEK));
System.out.println(year + "年" + month + "月" + date + "日" + "-" + week);
System.out.println(hour + ":" + minute + ":" + second);
}
private static String getWeek(int i) {
String[] weeks = { "", "星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
return weeks[i];
}
}