如何在当前日期添加日期?

时间:2015-11-27 02:03:14

标签: android

我想在当前日期添加90天,这是我的代码。我在网上尝试了一些例子,但它似乎没有用。

    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
    Calendar date = Calendar.getInstance();
    couponcreated = dateFormat.format(date);

    date.add(Calendar.DATE,90);
    SimpleDateFormat dateFormat1 = new SimpleDateFormat("dd-MM-yyyy");
    couponexpires = dateFormat1.format(date.getTime());

    couponexpiredate.setText(couponexpires);

但是,我收到错误,导致我的应用程序崩溃。

 java.lang.RuntimeException: Unable to start activity ComponentInfo{info.androidhive.loginandregistration/info.androidhive.loginandregistration.CouponReceivePageActivity}: java.lang.IllegalArgumentException: Bad class: class java.util.GregorianCalendar
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2295)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
        at android.app.ActivityThread.access$700(ActivityThread.java:159)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:5419)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:525)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1209)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1025)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.IllegalArgumentException: Bad class: class java.util.GregorianCalendar
        at java.text.DateFormat.format(DateFormat.java:296)
        at java.text.Format.format(Format.java:93)
        at info.androidhive.loginandregistration.CouponReceivePageActivity.onCreate(CouponReceivePageActivity.java:55)
        at android.app.Activity.performCreate(Activity.java:5372)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)

        at android.app.ActivityThread.access$700(ActivityThread.java:159)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)  
        at android.os.Handler.dispatchMessage(Handler.java:99)    
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:5419)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:525)

这是我的logcat代码。

1 个答案:

答案 0 :(得分:1)

您的错误是您第一次尝试格式化日期时 你应该写:

couponcreated = dateFormat.format(date.getTime());

而不是

couponcreated = dateFormat.format(date);

因为日历无法直接格式化,您需要使用getTime()函数从日历中获取日期