我想从 Java 中的当前日期中减去 n 天。
我怎么做?
您不必使用日历。你可以玩时间戳:
Date d = initDate();//intialize your date to any date
Date dateBefore = new Date(d.getTime() - n * 24 * 3600 * 1000 l ); //Subtract n days
更新 不要忘记在 1000 结束前添加“l”。
请考虑以下警告:
1000*60*60*24
在闰秒、夏令时等情况下,向 java 日期添加毫秒数会偶尔向原始日期添加零天或两天。如果您需要 100% 确定只添加一天,则此解决方案不适合使用。
这将减去当前日期的十天(在 Java 8 之前):
int x = -10;
Calendar cal = GregorianCalendar.getInstance();
cal.add( Calendar.DAY_OF_YEAR, x);
Date tenDaysAgo = cal.getTime();
如果您使用的是 Java 8,则可以使用新的日期和时间 API ( http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html ):
LocalDate tenDaysAgo = LocalDate.now().minusDays(10);
如需将新类型转换为旧类型,反之亦然,请参阅:在 java.time.LocalDateTime 和 java.util.Date 之间转换
我找到了这个完美的解决方案并且可能有用,您可以根据需要直接获取格式:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -90); // I just want date before 90 days. you can give that you want.
SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd"); // you can specify your format here...
Log.d("DATE","Date before 90 Days: " + s.format(new Date(cal.getTimeInMillis())));
谢谢。
public static void main(String args[]) throws ParseException {
String[] days = { "Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday" };
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
Date dt1 = format1.parse("20/10/2013");
Calendar c = Calendar.getInstance();
c.setTime(dt1);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
long diff = Calendar.getInstance().getTime().getTime() ;
System.out.println(dayOfWeek);
switch (dayOfWeek) {
case 6:
System.out.println(days[dayOfWeek - 1]);
break;
case 5:
System.out.println(days[dayOfWeek - 1]);
break;
case 4:
System.out.println(days[dayOfWeek - 1]);
break;
case 3:
System.out.println(days[dayOfWeek - 1]);
break;
case 2:
System.out.println(days[dayOfWeek - 1]);
break;
case 1:
System.out.println(days[dayOfWeek - 1]);
diff = diff -(dt1.getTime()- 3 );
long valuebefore = dt1.getTime();
long valueafetr = dt1.getTime()-2;
System.out.println("DATE IS befor subtraction :"+valuebefore);
System.out.println("DATE IS after subtraction :"+valueafetr);
long x= dt1.getTime()-(2 * 24 * 3600 * 1000);
System.out.println("Deducted date to find firday is - 2 days form Sunday :"+new Date((dt1.getTime()-(2*24*3600*1000))));
System.out.println("DIffrence from now on is :"+diff);
if(diff > 0) {
diff = diff / (1000 * 60 * 60 * 24);
System.out.println("Diff"+diff);
System.out.println("Date is Expired!"+(dt1.getTime() -(long)2));
}
break;
}
}
正如@Houcem Berrayana 所说
如果您想使用,n>24
那么您可以使用如下代码:
Date dateBefore = new Date((d.getTime() - n * 24 * 3600 * 1000) - n * 24 * 3600 * 1000);
假设您想查找最近 30 天的日期,那么您将使用:
Date dateBefore = new Date((d.getTime() - 24 * 24 * 3600 * 1000) - 6 * 24 * 3600 * 1000);