//日期转字符串,根据需要调整格式
@Testpublic voidDateToString(){
Date currentTime= newDate();
SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString=formatter.format(currentTime);
System.out.println(dateString);
}字符串转日期
void StrToDate() throwsParseException {
String dateStr= "2019-01-19";
SimpleDateFormat format= new SimpleDateFormat("yyyy-MM-dd");
Date date= null;
date=format.parse(dateStr);
System.out.println(date);
}获取本月第一天
void getMonthFirstDay() ParseException {
SimpleDateFormat format= );
Calendar cal=Calendar.getInstance();获取当前日期
cal.set(Calendar.DAY_OF_MONTH,1);设置为1号,当前日期既为本月第一天
String monthFirstDay =format.format(cal.getTime());
System.out.println(monthFirstDay);
}获取本月最后一天
void getMonthLastDay() 获取当前日期
cal.set(Calendar.DAY_OF_MONTH,cal.getActualMaximum(Calendar.DAY_OF_MONTH));
String monthLastDay=format.format(cal.getTime());
System.out.println(monthLastDay);
}获取上个月第一天。最后一天同理
void getLastMonthFirstDay() 获取当前日期
cal.add(Calendar.MONTH,-1);
cal.set(Calendar.DAY_OF_MONTH,1);通过Calendar获取年月日时分秒
void testCalendar() ParseException {
Calendar cal=Calendar.getInstance();赋值时年月日时分秒常用的6个值,注意月份下标从0开始,所以取月份要+1
System.out.println("年:" +cal.get(Calendar.YEAR));
System.out.println("月:" + (cal.get(Calendar.MONTH) + 1));
System.out.println("日:" +cal.get(Calendar.DAY_OF_MONTH));
System.out.println("时:" +cal.get(Calendar.HOUR_OF_DAY));
System.out.println("分:" +cal.get(Calendar.MINUTE));
System.out.println("秒:" +cal.get(Calendar.SECOND));
}得到两个时间相隔的天数
void getBetweenDay() ParseException{
String dateStr1= "2019-01-01";
String dateStr2= "2019-01-19";
SimpleDateFormat format= );
Date date1=format.parse(dateStr1);
Date date2=format.parse(dateStr2);
Long inteverDay= (date2.getTime()-date1.getTime())/(1000*60*60*24);
System.out.println(inteverDay);
}当前日期加一天
void addCurrentDay() ParseException {
String datess= "2019-02-28");
Date parse=format.parse(datess);
Calendar cal=Calendar.getInstance();cal.setTime(parse);
cal.add(Calendar.DAY_OF_YEAR,+1);
String monthFirstDay=Calendar转换成date
void CalToDate() ParseException {
Calendar cal=Calendar.getInstance();
Date date=cal.getTime();
}date转换成Calendar
void DateToCal() Calendar.getInstance();
Date date= Date();
cal.setTime(date);
}获得当前周周一的日期
getMonday(){
Date date= Date();
Calendar c=Calendar.getInstance();
c.setTime(date);monday可以替换成任意星期几
c.set(Calendar.DAY_OF_WEEK,Calendar.MONDAY);
String dateStr= ).format(c.getTime());
System.out.println(dateStr);
}判断两个时间是否在同一周
booleanisSameWeekDates(Date date1,Date date2) {
Calendar cal1=Calendar.getInstance();
Calendar cal2=Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);int subYear = cal1.get(Calendar.YEAR) -cal2.get(Calendar.YEAR);if (0 ==subYear) {if (cal1.get(Calendar.WEEK_OF_YEAR) ==cal2.get(Calendar.WEEK_OF_YEAR)){return true;
}
}else if (1 == subYear && 11 ==cal2.get(Calendar.MONTH)) {如果12月的最后一周横跨来年第一周的话则最后一周即算做来年的第一周
if (-1 == subYear && 11 ==cal1.get(Calendar.MONTH)) {;
}
}false;
}