Android - 如何减去当前日期与任何其他日期

时间:2013-12-09 10:33:58

标签: android date

我的活动中有2个日期选择器,1个用于分配日期而另一个是截止日期,现在我想要做的是当用户设置两个日期时我希望文本视图中的日期不同。

实施例。如果分配日期是12-05-2013,截止日期是14-05-2013,则文本视图应该显示“我已经完成了2天”。

现在问题来了,当日期变化,如果今天是13-05-2013然后我想在文本视图中显示“1天的左”,这意味着文本视图应该自动更新当前日期。

public class Code {
public static Calendar AssignDate;
public static Calendar DueDate;
}

imageViewSubmit.setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0) {
            Code.title = editTextTitle.getText().toString().trim();
            Code.description = editTextDesc.getText().toString().trim();
            Code.diff = Code.DueDate.getTimeInMillis()
                    - Code.AssignDate.getTimeInMillis();
            Code.days = Code.diff / (24 * 60 * 60 * 1000);

            String strDays = String.valueOf(Code.days);
            textViewDiff.setText(strDays);
            String dateDifference = textViewDiff.getText().toString().trim();
        }
    });            

2 个答案:

答案 0 :(得分:1)

希望这个例子可以帮到你。

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateDifferenceExample {

    /**
     * @param args
     */
    public static void main(String[] args) {

        String dateStart = "12/09/2013 09:29:58";
        String dateStop = "12/15/2013 10:31:48";

        // HH converts hour in 24 hours format (0-23), day calculation
        SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

        Date d1 = null;
        Date d2 = null;

        try {
            d1 = format.parse(dateStart);
            d2 = format.parse(dateStop);

            // in milliseconds
            long diff = d2.getTime() - d1.getTime();

            long diffSeconds = diff / 1000 % 60;
            long diffMinutes = diff / (60 * 1000) % 60;
            long diffHours = diff / (60 * 60 * 1000) % 24;
            long diffDays = diff / (24 * 60 * 60 * 1000);

            System.out.print(diffDays + " days, ");
            System.out.print(diffHours + " hours, ");
            System.out.print(diffMinutes + " minutes, ");
            System.out.print(diffSeconds + " seconds.");

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

答案 1 :(得分:0)

String date1 = "12-05-2013";
String date2 = "14-05-2013";
Calendar date1Calendar = Calendar.getInstance();
date1Calendar.setTime(new SimpleDateFormat("dd-MM-yyyy").parse(inputDateString));
Calendar date2Calendar = Calendar.getInstance();
date2Calendar.setTime(new SimpleDateFormat("dd-MM-yyyy").parse(inputDateString));
if(date2Calendar.after(date1Calendar))
    String daysLeft = "Days Left: " + (date2Calendar.get(Calendar.DAY_OF_MONTH) -(date1Calendar.get(Calendar.DAY_OF_MONTH)));