一、关于Date
private static void dateTest(){
//定义时区,可以避免虚拟机时间与系统时间不一致的问题
// TimeZone.setDefault(TimeZone.getTimeZone("North America/Washington"));
TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));
//方法一:该方法返回当前的计算机时间,时间的表达格式为当前计算机时间和GMT时间(格林威治时间)1970年1月1号0时0分0秒所差的毫秒数。
long TimeNow = System.currentTimeMillis();
//可以将其转换为date类型
System.out.println(new Date(TimeNow));
//方法二:Date方式,输出现在时间
Date nowTime = new Date();
System.out.println(nowTime);
//时间格式化
SimpleDateFormat matter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(matter.format(nowTime));//方法三:SimpleDateFormat方式,完整输出现在时间
//date不能根据“2018-01-23”这种String来创建指定时间,只能通过如下方式:
//方式一:new Date(year,month,day)
Date date = new Date(118,0,23);
System.out.println(matter.format(date));
//方式二
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date1 = dateFormat.parse("2018-01-23");
System.out.println(date1);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
二、关于Calendar
Calendar最好的一点是可以加减
private static void calendarTest(){
Calendar cal = Calendar.getInstance();
//三天前
cal.add(Calendar.DAY_OF_MONTH, -3);
int year =cal.get(Calendar.YEAR);
int month =cal.get(Calendar.MONTH)+1;
int day =cal.get(Calendar.DAY_OF_MONTH);
int hour =cal.get(Calendar.HOUR_OF_DAY);
int minute =cal.get(Calendar.MINUTE);
int seconds =cal.get(Calendar.SECOND);
System.out.println(year+"-"+month+"-"+day+" "+hour+":"+minute+":"+seconds);
}
三、Date与Calendar相互转换
private static void calendarAndDate(){
//Calendar转化为Date
Calendar cal1=Calendar.getInstance();
Date date1=cal1.getTime();
System.out.println(date1);
//Date转化为Calendar
Date date2=new Date();
Calendar cal2=Calendar.getInstance();
cal2.setTime(date2);
int year =cal2.get(Calendar.YEAR);
int month =cal2.get(Calendar.MONTH)+1;
int day =cal2.get(Calendar.DAY_OF_MONTH);
int hour =cal2.get(Calendar.HOUR_OF_DAY);
int minute =cal2.get(Calendar.MINUTE);
int seconds =cal2.get(Calendar.SECOND);
System.out.println(year+"-"+month+"-"+day+" "+hour+":"+minute+":"+seconds);
}