望知道怎么取的大神帮帮我,Java 获一天从00:00:00到23:59:59时间段的所有时间,每隔五分钟取一次。希望提供代码。
------解决方案--------------------
如果只是去除常量时间,使用循环拼接一些字符就可以啊。
------解决方案--------------------
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class Test {
public static void main(String[] args) {
Date date = new Date();
List<Date> ds = test(date);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (Date d : ds) {
System.out.println(sdf.format(d));
}
}
static List<Date> test(Date date) {
Date start = dayStartDate(date);//转换为天的起始date
Date nextDayDate = nextDay(start);//下一天的date
List<Date> result = new ArrayList<Date>();
while (start.compareTo(nextDayDate) < 0) {
result.add(start);
//日期加5分钟
start = addFiveMin(start, 5);
}
return result;
}
private static Date addFiveMin(Date start, int offset) {
Calendar c = Calendar.getInstance();
c.setTime(start);
c.add(Calendar.MINUTE, offset);
return c.getTime();
}
private static Date nextDay(Date start) {
Calendar c = Calendar.getInstance();
c.setTime(start);
c.add(Calendar.DATE, 1);
return c.getTime();
}
private static Date dayStartDate(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
return c.getTime();
}
}
------解决方案--------------------
calendar日历类,每次对分钟 **.add(Calendar.MINUTE,5)
------解决方案--------------------
public static void main(String[] args) {
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
List<Date> list = getTimeSegment(2014, 7, 1);
for(Date date : list){
System.out.println(fmt.format(date));
}
}
public static List<Date> getTimeSegment(int year, int month, int day){
Calendar cal = Calendar.getInstance();
cal.set(year, month-1, day, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
long startTime = cal.getTimeInMillis();
cal.set(year, month-1, day, 23, 59, 59);
long endTime = cal.getTimeInMillis();
final int seg = 5*60*1000;//五分钟
ArrayList<Date> result = new ArrayList<Date>((int)((endTime-startTime)/seg+1));
for(long time = startTime;time<=endTime;time+=seg){
result.add(new Date(time));
}
return result;
}
------解决方案--------------------
void add(int field, int amount);
Calendar.getInstance().add(Calendar.MINUTE, 5 );
然后比较。