挺low的代码orz:
public class DateUtil {
private static int mYear; //当前年
private static int mMonth; //当前月
private static int mDay;
private static int mWeek;
private static int dayAmount = 6;//往后天数
//获取当前日期往后一周的时间
public static List<String> getNextSevenData() {
List<String> dates = new ArrayList<>();
final Calendar c = Calendar.getInstance();
c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
int maxDay = c.getActualMaximum(Calendar.DATE);//该月最大天数
mYear = c.get(Calendar.YEAR);// 获取当前年份
mMonth = c.get(Calendar.MONTH) + 1;// 获取当前月份
mDay = c.get(Calendar.DAY_OF_MONTH);
mWeek = c.get(Calendar.DAY_OF_WEEK);
//当天
String date = mYear + "-" + mMonth + "-" + mDay;
dates.add(date);
//往后6天
for (int i = 0; i < dayAmount; i++) {
if (mDay + 1 > maxDay) { //超过最大天数
if (mMonth + 1 > 12) {//该年最后一个月
mYear = mYear + 1;
mMonth = 1;
} else {
mMonth = mMonth + 1;
}
mDay = 1;
} else {
mDay = mDay + 1;
}
date = mYear + "-" + mMonth + "-" + mDay;
dates.add(date);
}
return dates;
}
//根据当前时间 分割时间段 获取时间列表
public static List<String> getTimeList(int intervalTime, String date) {
List<String> timeList = new ArrayList<>();
int intervaTimestamp = intervalTime * 60 * 1000;//间隔多少分钟的时间戳
String pattern = "yyyy-MM-dd HH:mm";//时间格式 yyyy-MM-dd HH:mm:ss yyyy-MM-dd yyyy年MM月dd日 HH时mm分ss秒 yyyy年MM月dd日等
String startTime = date + " " + "09:00:00";//开始时间 "样式如2017-11-11 11:11:11"
String finalTime = date + " " + "21:00:00";//结束时间
String currentTime = getCurDate(pattern);//当前时间
long startTimestamp = getStringToDate(startTime, pattern);
long finalTimestamp = getStringToDate(finalTime, pattern);
long currentTimestamp = getStringToDate(currentTime, pattern);
int times = (int) (finalTimestamp - startTimestamp) / intervaTimestamp;//有多少间隔
for (int i = 0; i <= times; i++) {
if (startTimestamp >= currentTimestamp) {
timeList.add(getDateToString(startTimestamp, pattern));
}
startTimestamp = startTimestamp + intervaTimestamp;//当前时间 向后推移时间段
}
return timeList;
}
//获取当前系统时间
public static String getCurDate(String pattern) {
SimpleDateFormat sDateFormat = new SimpleDateFormat(pattern);
return sDateFormat.format(new java.util.Date());
}
//根据时间戳 返回日期
public static String getDateToString(long milSecond, String pattern) {
Date date = new Date(milSecond);
SimpleDateFormat format = new SimpleDateFormat(pattern);
return format.format(date);
}
//根据日期及格式 返回时间戳
public static long getStringToDate(String dateString, String pattern) {
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
Date date = new Date();
try {
date = dateFormat.parse(dateString);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return date.getTime();
}
}
运行:
//当前时间为 "2017-11-30 11:43:45"
DateUtil.getTimeList(30,"2017-11-30");
DateUtil.getTimeList(30,"2018-11-30");
结果: