如何在当前日期中添加 30 天



我想在当前日期中添加 30 天 我搜索了很多,但没有得到正确的解决方案。

我的代码

 Date date = new Date();
 SimpleDateFormat df = new SimpleDateFormat("YYYY-MM-dd");
 Calendar c1 = Calendar.getInstance();
 String currentdate = df.format(date);
 try {
     c1.setTime(df.parse(currentdate));
     c1.add(Calendar.DATE, 30);
     df = new SimpleDateFormat("yyyy-MM-dd");
     Date resultdate = new Date(c1.getTimeInMillis());
     String dueudate = df.format(resultdate);
     Toast.makeText(this, dueudate, Toast.LENGTH_SHORT).show();
 } catch (ParseException e) {
     e.printStackTrace();
 }

此代码的输出为:2019-01-29我不知道为什么它显示这个输出,任何人都可以帮助我。

你需要使用

c1.add(Calendar.DAY_OF_YEAR, 30);

而不是

c1.add(Calendar.DATE, 30);

试试这个

    Date date = new Date();
    SimpleDateFormat df  = new SimpleDateFormat("YYYY-MM-dd");
    Calendar c1 = Calendar.getInstance();
    String currentDate = df.format(date);// get current date here
    // now add 30 day in Calendar instance 
    c1.add(Calendar.DAY_OF_YEAR, 30);
    df = new SimpleDateFormat("yyyy-MM-dd");
    Date resultDate = c1.getTime();
    String     dueDate = df.format(resultDate);
    // print the result
    Utils.printLog("DATE_DATE :-> "+currentDate);
    Utils.printLog("DUE_DATE :-> "+dueDate);

输出

2019-06-04 14:43:02.438 E/XXX_XXXX: DATE_DATE :-> 2019-06-04
2019-06-04 14:43:02.438 E/XXX_XXXX: DUE_DATE :-> 2019-07-04

另一个更简单的选择,如果在Java 8上,使用java.time包,它提供了在任何时间单位的当前日期执行加/减的函数,例如:

import java.time.LocalDate;

 LocalDate date =  LocalDate.now().plusDays(30);
 //or
 LocalDate date =  LocalDate.now().plus(30, ChronoUnit.DAYS);

Calendar.getInstance()为您提供当前时间。您无需为此创建另一个Date对象。

    Calendar current = Calendar.getInstance();
    current.add(Calendar.DATE, 30);
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    Date resultdate = new Date(current.getTimeInMillis());
    String dueudate = df.format(resultdate);
    System.out.println("" + dueudate);

1(从日期转到毫秒。2(创建一个值为30L * 24L * 60L * 60L * 1000L的长变量。3(将此值添加到您在步骤 1 中获得的 millis 中4(再次从这个总和回到日期。

编辑:存储 millis 的变量应该是长整型,而不是整数。编辑2:在每个数字旁边添加"L"保证我们不会溢出。

最新更新