1、String和Date转换;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// 将Date类型的日期格式化为String类型
String str = sdf.format(new Date());
// 将String类型的时间转换为Date
String date = "2018-11-23";
Date parse = sdf.parse(date);
2、计算两个时间日期中间相差天数
try{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date1 = "2018-12-11";
String date2 = "2018-12-13";
Date begin = sdf.parse(date1);
Date end=sdf.parse(date2);
Calendar cld=Calendar.getInstance();
cld.setTime(begin);
long time1 = cld.getTimeInMillis();
cld.setTime(end);
long time2 = cld.getTimeInMillis();
long between_days=(time2-time1)/(1000*3600*24);
int day=Integer.parseInt(String.valueOf(between_days));
System.out.println(day);//day为2
}catch(ParseException e){
e.printStackTrace();
}
3、判断两个Date 时间的大小:beginTime<endTime,beginTime+1天;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date beginTime = new Date();
Date endTime = null;
try{
endTime = sdf.parse("2019-09-20");
}catch (ParseException e){
endTime = new Date();
}
System.out.println("endTime" + sdf.format(endTime));
if(beginTime.before(endTime)){
Calendar cld=Calendar.getInstance();
cld.setTime(beginTime);
cld.add(Calendar.DATE, 1);
beginTime=cld.getTime();
}
System.out.println(sdf.format(beginTime));
System.out.println(sdf.format(endTime));
4、 给当前日期加减天数,-3天
Date d = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currdate = format.format(d);
System.out.println("现在的日期是:" + currdate);
Calendar ca = Calendar.getInstance();
ca.add(Calendar.DATE, -3);// num为增加的天数,可以改变的
d = ca.getTime();
String enddate = format.format(d);
System.out.println("增加天数以后的日期:" + enddate);
5、给指定日期加减天数,+5天
String createDate = "2000-01-01 09:20:25";
System.out.println("指定的日期为:"+createDate);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
int day = 5;
try {
Date date = sdf.parse(createDate);
Calendar cl = Calendar.getInstance();
cl.setTime(date);
cl.add(Calendar.DATE, day);
String temp = "";
temp = sdf.format(cl.getTime());
System.out.println("加上天数的日期:"+temp);
} catch (ParseException e) {
e.printStackTrace();
}
6、SimpleDateFormat是线程安全的吗?
非常不幸,DateFormat 的所有实现,包括 SimpleDateFormat 都不是线程安全的,因此你不应该在多线程序中使用,除非是在对外线程安全的环境中使用,如 将 SimpleDateFormat 限制在 ThreadLocal 中。如果你不这么做,在解析或者格式化日期的时候,可能会获取到一个不正确的结果。因此,从日期、时间处理的所有实践来说,我强力推荐 joda-time 库。
7、如何格式化日期?
Java 中,可以使用 SimpleDateFormat 类或者 joda-time 库来格式日期。DateFormat 类允许你使用多种流行的格式来格式化日期。参见答案中的示例代码,代码中演示了将日期格式化成不同的格式,如 dd-MM-yyyy 或 ddMMyyyy。