如何在android中获取前一天和第二天的日期?

时间:2015-08-19 07:34:25

标签: android date

我创建了一个包含三个Buttons的布局。我的想法是使用这三个按钮作为日期选择器。这三个按钮是-Today+。 如果我按今天按钮显示今天的日期。当我按-时,它会显示昨天的日期。如果我按+,它会显示明天的日期。没问题。但它只能工作一次。我的要求是,只要我按-它必须显示前一天的日期,即19-Aug-201518-Aug-201517-Aug-2015等,我的代码是

 imgtoday.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            googleMap.clear();
            Date date1=new Date(System.currentTimeMillis());
            SimpleDateFormat sdf=new SimpleDateFormat("dd-MMM-yyyy");
            String date=sdf.format(date1);
            drawRoute(date);
            imgHistory.setClickable(false);
            imgHistory.setBackgroundResource(R.drawable.btn_disabled);
            calculateDistance(date);
        }
    });

    previousDay=(Button)findViewById(R.id.button9);
    nextDay=(Button)findViewById(R.id.button11);

    previousDay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            googleMap.clear();
            Date date1=new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24));
            SimpleDateFormat sdf=new SimpleDateFormat("dd-MMM-yyyy");
            String date=sdf.format(date1);
            drawRoute(date);
            calculateDistance(date);
        }
    });

    nextDay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            googleMap.clear();
            Date date1=new Date(System.currentTimeMillis() + (1000 * 60 * 60 * 24));
            SimpleDateFormat sdf=new SimpleDateFormat("dd-MMM-yyyy");
            String date=sdf.format(date1);
            drawRoute(date);
            calculateDistance(date);
        }
    });

任何人都请帮忙。感谢。

8 个答案:

答案 0 :(得分:13)

使用日历:

Calendar cal = Calendar.getInstance(); 
cal.setTime(TODAY); 
cal.add(Calendar.DAY_OF_MONTH, 1); //Adds a day
cal.add(Calendar.DAY_OF_MONTH, -1); //Goes to previous day
yourDate = cal.getTime();

答案 1 :(得分:2)

这是我用于递增和递减日期的代码

/**
 * Get next date from current selected date
 *
 * @param date date
 */
public Date incrementDateByOne(Date date) {
    Calendar c = Calendar.getInstance();
    c.setTime(date);
    c.add(Calendar.DATE, 1);
    Date nextDate = c.getTime();
    return nextDate;
}

/**
 * Get previous date from current selected date
 *
 * @param date date
 */
public Date decrementDateByOne(Date date) {
    Calendar c = Calendar.getInstance();
    c.setTime(date);
    c.add(Calendar.DATE, -1);
    Date previousDate = c.getTime();
    return previousDate;
}

我希望它有所帮助!

答案 2 :(得分:1)

您可以使用 Joda-Time 库轻松获取下一天和前几天。

https://github.com/JodaOrg/joda-time

https://github.com/dlew/joda-time-android

实施例

LocalDate dateTime =  LocalDate.now()  // Here 'date' is the current date
dateTime = dateTime.plusDays(1); // get the next day date

您可以找到更多内置函数,例如dateTime.plusYear(1)等。

代码

 previousDay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            googleMap.clear();
            LocalDate startDate = LocalDate.now() ;
            startDate = startDate.plusDays(-1); 
            DateTimeFormatter fmt1 = DateTimeFormat.forPattern("You Format here");
            String DateInstrg = date.toString(fmt1);
            // rest of you code
        }
    });

    nextDay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            googleMap.clear();
             LocalDate startDate = LocalDate.now() 
            startDate = startDate.plusDays(1); 
            DateTimeFormatter fmt1 = DateTimeFormat.forPattern("You Format here");
            String DateInstrg = date.toString(fmt1);
            // rest of you code
        }
    });

答案 3 :(得分:1)

按照方法

获取上一个日期
08-19 13:03:13.662    3700-3700/com.example.jayakarthik.sampleanim E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.jayakarthik.sampleanim, PID: 3700
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jayakarthik.sampleanim/com.example.jayakarthik.sampleanim.MainActivity}: android.view.InflateException: Binary XML file line #8: Error inflating class com.example.jayakarthik.sampleanim.CircularCountdown
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2252)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2301)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
            at android.os.Handler.dispatchMessage(Handler.java:106)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5212)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: android.view.InflateException: Binary XML file line #8: Error inflating class com.example.jayakarthik.sampleanim.CircularCountdown
            at android.view.LayoutInflater.createView(LayoutInflater.java:603)
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
            at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:294)
            at android.app.Activity.setContentView(Activity.java:1929)
            at com.example.jayakarthik.sampleanim.MainActivity.onCreate(MainActivity.java:12)
            at android.app.Activity.performCreate(Activity.java:5240)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2216)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2301)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
            at android.os.Handler.dispatchMessage(Handler.java:106)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5212)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NoSuchMethodException: <init> [class android.content.Context, interface android.util.AttributeSet]
            at java.lang.Class.getConstructorOrMethod(Class.java:472)
            at java.lang.Class.getConstructor(Class.java:446)
            at android.view.LayoutInflater.createView(LayoutInflater.java:568)
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
            at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:294)
            at android.app.Activity.setContentView(Activity.java:1929)
            at com.example.jayakarthik.sampleanim.MainActivity.onCreate(MainActivity.java:12)
            at android.app.Activity.performCreate(Activity.java:5240)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2216)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2301)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
            at android.os.Handler.dispatchMessage(Handler.java:106)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5212)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
            at dalvik.system.NativeStart.main(Native Method)

按照方法

获取下一天的日期
public static boolean isPreviousday(Date currenTimeZone) {
    boolean previousdate = false;
    Calendar c1 = Calendar.getInstance(); // today
    c1.add(Calendar.DAY_OF_YEAR, -1); // yesterday

    Calendar c2 = Calendar.getInstance();
    c2.setTime(currenTimeZone);
    if (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR)
            && c1.get(Calendar.DAY_OF_YEAR) == c2.get(Calendar.DAY_OF_YEAR)) {
        return previousdate = true;
    } else {
        return previousdate = false;
    }
}

答案 4 :(得分:0)

Crate date1全球私有字段并在onCreate中初始化: date1=new Date(System.currentTimeMillis());

OnClick方法,例如: date1=new Date(date1.getTime() +- (1000 * 60 * 60 * 24));

答案 5 :(得分:0)

 c = Calendar.getInstance();
        System.out.println("Current time => " + c.getTime());
        df = new SimpleDateFormat("dd-MMM-yyyy");
        formattedDate = df.format(c.getTime());
        String str1 = this.days[c.get(Calendar.DAY_OF_WEEK)-1];
        textView.setText(formattedDate);
    next.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            c.add(Calendar.DATE, 1);
           // c.add(Calendar.DAY_OF_WEEK,1);
            formattedDate = df.format(c.getTime());

            Log.v("NEXT DATE : ", formattedDate);
            textView.setText(formattedDate);

        }
    });
    previous.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            c.add(Calendar.DATE, -1);
          //  c.add(Calendar.DAY_OF_WEEK,-1);
            formattedDate = df.format(c.getTime());

            Log.v("PREVIOUS DATE : ", formattedDate);
            textView.setText(formattedDate);
        }
    });

答案 6 :(得分:-1)

修改现有代码,例如:

int plusButtonPressed = 1;
int minusButtonPressed = 1;

previousDay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            googleMap.clear();
            Date date1=new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24) * minusButtonPressed);
            SimpleDateFormat sdf=new SimpleDateFormat("dd-MMM-yyyy");
            String date=sdf.format(date1);
            drawRoute(date);
            calculateDistance(date);
            minusButtonPressed += 1;
        }
    });

    nextDay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            googleMap.clear();
            Date date1=new Date(System.currentTimeMillis() + (1000 * 60 * 60 * 24) * plusButtonPressed);
            SimpleDateFormat sdf=new SimpleDateFormat("dd-MMM-yyyy");
            String date=sdf.format(date1);
            drawRoute(date);
            calculateDistance(date);
            plusButtonPressed += 1;
        }
    });

答案 7 :(得分:-1)

您不需要库,您可以使用Calendar实例。 http://developer.android.com/reference/java/util/Calendar.html 有一个很长的解释,但这是一个摘录:

  

使用模式。要激发add()和roll()的行为,请考虑具有月,日和年的递增和递减按钮的用户界面组件以及基础GregorianCalendar。如果界面读取1999年1月31日并且用户按下月份增量按钮,它应该读取什么?如果底层实现使用set(),它可能会读到1999年3月3日。更好的结果将是1999年2月28日。此外,如果用户再次按月增量按钮,它应该是1999年3月31日,而不是3月28日通过保存原始日期并使用add()或roll(),取决于是否应该影响更大的字段,用户界面的行为可以像大多数用户直观期望的那样。

     

注意:您应该始终使用roll并添加而不是尝试直接在Calendar的字段上执行算术运算。 Calendar子类很可能具有非线性行为的字段,例如在非闰年期间缺少数月或数天。子类&#39;添加和滚动方法会考虑到这一点,而简单的算术操作可能会产生无效结果。

所以你可以这样做:

final SimpleDateFormat sdf=new SimpleDateFormat("dd-MMM-yyyy");
Calendar actualDate = Calendar.getInstance();
imgtoday.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            googleMap.clear();
            actualDate=Calendar.getInstance();
            String date=sdf.format(actualDate.getTime());
            drawRoute(date);
            imgHistory.setClickable(false);
            imgHistory.setBackgroundResource(R.drawable.btn_disabled);
            calculateDistance(date);
        }
    });
previousDay=(Button)findViewById(R.id.button9);
nextDay=(Button)findViewById(R.id.button11);

previousDay.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        googleMap.clear();
//modify actual date, removing one day
        actualDate.add(Calendar.DAY_OF_MONTH,-1);
        String date=sdf.format(actualDate.getTime());
        drawRoute(date);
        calculateDistance(date);
    }
});

nextDay.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        googleMap.clear();
        actualDate.add(Calendar.DAY_OF_MONTH,1);
        String date=sdf.format(actualDate.getTime());
        drawRoute(date);
        calculateDistance(date);
    }
});

PS:不需要每次都重新初始化相同的日期格式,只需要一次。