1、最简单的获取当前时间的方法
Date date = new Date();
SimpleDateFormat f= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String nowday = f.format(date);
2、分别获取当前的年月日时分秒以及星期几
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH)+1;
int day = c.get(Calendar.DATE);
int hour = c.get(Calendar.HOUR);
int min = c.get(Calendar.MINUTE);
int sec = c.get(Calendar.SECOND);
//周一到周日分别对应1~7
int week = c.get(Calendar.DAY_OF_WEEK)-1 == 0 ? 7 : c.get(Calendar.DAY_OF_WEEK)-1 ;
3、计算两个时间的差值(稍改一下也可以作为判断两个时间大小的方法)
String startT = "2019-06-06 12:15:48";
String endT = "2019-09-15 16:45:26";
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date endDate = sdf.parse(endtime);
Date nowDate=sdf.parse(starttime);
//差值秒
long diff = (endDate.getTime() - nowDate.getTime())/1000;
4、获取某个时间未来或之间几天的日期
String tarTime = "2019-05-05";
Integer tarDay = 6;
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(tarTime);
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DAY_OF_MONTH,tarDay);
date = c.getTime();
String orTime = sdf.format(date);
5、判断某个时间日期是周几
String tarTime = "2019-05-06";
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(format.parse(pTime));
String[] weeks = ["星期一","星期二","星期三","星期四","星期五","星期六","星期日"];
int curIndex = c.get(Calendar.DAY_OF_WEEK)-2 == -1 ? 6 : c.get(Calendar.DAY_OF_WEEK)-2;
String week = weeks[curIndex];
6、获取某个时间段内星期日(星期几可以自己指定)的天数
String startT="2019-06-15";String endT = "2019-09-16";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
List<String> tarDateList = new ArrayList<>();
Calendar c = Calendar.getInstance();
String[] dateArr = {startT, endT};
//计算并存储起始时间和结束时间
Date[] dates = new Date[dateArr .length];
for (int i = 0; i < dateArr .length; i++) {
String[] ymd = dateArr [i].split("[^\\d]+");
cal.set(Integer.parseInt(ymd[0]), Integer.parseInt(ymd[1]) - 1, Integer.parseInt(ymd[2]));
dates[i] = cal.getTime();
}
for (Date date = dates[0]; date.compareTo(dates[1]) <= 0; ) {
//起始时间
cal.setTime(date);
//时间是周日的取出来
if (cal.get(Calendar.DAY_OF_WEEK) - 1 == 0) {
String format = sdf.format(date);
dateResult.add(format);
}
//时间加一天
cal.add(Calendar.DATE, 1);
date = cal.getTime();
}