我想在今天的日期之前7天获取日期.我正在使用SimpleDateFormat来获取今天的日期.
SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
Run Code Online (Sandbox Code Playgroud)
请指导我完成这个
我发现最有用的更新答案
SimpleDateFormat sdf=new SimpleDateFormat("dd/MM/yyyy");
String currentDateandTime = sdf.format(new Date());
Date cdate=sdf.parse(currentDateandTime);
Calendar now2= Calendar.getInstance();
now2.add(Calendar.DATE, -7);
String beforedate=now2.get(Calendar.DATE)+"/"+(now2.get(Calendar.MONTH) + 1)+"/"+now2.get(Calendar.YEAR);
Date BeforeDate1=sdf.parse(beforedate);
cdate.compareTo(BeforeDate1);
Run Code Online (Sandbox Code Playgroud)
谢谢你的回复
Les*_*zek 23
使用java.util.Calendar,将其设置为今天的日期,然后减去7天.
Calendar cal = GregorianCalendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.DAY_OF_YEAR, -7);
Date 7daysBeforeDate = cal.getTime();
Run Code Online (Sandbox Code Playgroud)
编辑:在Java 8中,通过使用java.time包中的类可以更轻松地完成:
final LocalDate date = LocalDate.now();
final LocalDate dateMinus7Days = date.minusDays(7);
//Format and display date
final String formattedDate = dateMinus7Days.format(DateTimeFormatter.ISO_LOCAL_DATE);
System.out.println(formattedDate);
Run Code Online (Sandbox Code Playgroud)
你可以尝试一下,
import java.util.Calendar;
public class AddDaysToCurrentDate {
public static void main(String[] args) {
//create Calendar instance
Calendar now = Calendar.getInstance();
System.out.println("Current date : " + (now.get(Calendar.MONTH) + 1)
+ "-"
+ now.get(Calendar.DATE)
+ "-"
+ now.get(Calendar.YEAR));
//add days to current date using Calendar.add method
now.add(Calendar.DATE,1);
System.out.println("date after one day : " + (now.get(Calendar.MONTH) + 1)
+ "-"
+ now.get(Calendar.DATE)
+ "-"
+ now.get(Calendar.YEAR));
//substract days from current date using Calendar.add method
now = Calendar.getInstance();
now.add(Calendar.DATE, -10);
System.out.println("date before 10 days : " + (now.get(Calendar.MONTH) + 1)
+ "-"
+ now.get(Calendar.DATE)
+ "-"
+ now.get(Calendar.YEAR));
}
}
/*
Typical output would be
Current date : 12-25-2007
date after one day : 12-26-2007
date before 10 days : 12-15-2007
*/
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14711 次 |
| 最近记录: |