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];
}
}