Heim > Fragen und Antworten > Hauptteil
我要获取最近30天的东西,endDate就是现在的时间,startDate是现在的时间减去30天,求startDate是怎么做的??????谢谢
String endDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
String startDate = "";
PHPz2017-04-17 17:10:12
如果不能使用java8,建议使用Calendar类来做,代码如下,add
方法第二个参数传递负值即可。
Calendar now = Calendar.getInstance();
now.add(Calendar.DAY_OF_MONTH, -30);
String endDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(now.getTime());
System.out.println(endDate);
java8版本可以使用下面的方法:
LocalDateTime now = LocalDateTime.now();
now = now.minus(30, ChronoUnit.DAYS);
System.out.println(now.toString());
巴扎黑2017-04-17 17:10:12
如下,最后格式根据需要转化下即可:
var startDate = new Date( new Date() - 24*60*60*1000 * 30 );
console.log('startDate: ' + startDate);
// startDate: Tue Jan 19 2016 15:42:19 GMT+0800 (CST)
迷茫2017-04-17 17:10:12
Date endDate = new Date();
Date startDate = new Date(endDate.getTime() - 30 * 24 * 60 * 60 * 1000);
怪我咯2017-04-17 17:10:12
public class Test {
public static void main(String[] args) {
Date endDate = new Date();
Date startDate = getDateBefore(new Date(),30);
}
private static Date getDateBefore(Date d, int day){
Calendar now =Calendar.getInstance();
now.setTime(d);
now.set(Calendar.DATE,now.get(Calendar.DATE)-day);
return now.getTime();
}
}
ringa_lee2017-04-17 17:10:12
import org.apache.commons.lang3.time.DateUtils;
Date now = new Date();
Date startDate = DateUtils.addDays(now, -30);