首页 > 解决方案 > 我如何将日期有序地放在每个按钮上?

问题描述

我有 7 个按钮。在第一个按钮上我显示当前日期,在第二个按钮上我希望它显示明天的日期,在第三个按钮上显示之后的日期,依此类推。

我尝试了几次使用Calendar,但当此活动打开时应用程序关闭。有人可以告诉我如何Calendar在我的情况下使用吗?或如何解决这个问题?

public class OrderActivity extends AppCompatActivity {

Button dateButton1, dateButton2;

Calendar calender = Calendar.getInstance();
Date today = new Date();


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_order);

    dateButton1 = (Button)findViewById(R.id.button5);
    dateButton2 = (Button)findViewById(R.id.button6);


    int amount = 1; // amount of days you want to add to the current date

    SimpleDateFormat formattedDate = new SimpleDateFormat("MM");

    today.setTime(System.currentTimeMillis()); //set to current date
    dateButton1.setText(formattedDate.format(today));


    //this code below cause app stoped when this activity start
    calender.add(Calendar.DATE, amount);
    String newDate = (String)(formattedDate.format(calender.getTime()));

    dateButton2.setText(formattedDate.format(newDate));

}}

这是我的最后一次构建,如何在 dateButton2 上应用下一个日期,在 dateButton3 上应用下一个日期等等?

到目前为止,当进入此活动时,应用程序已关闭,这在 logcat 上

> java.lang.IllegalArgumentException: Cannot format given Object as a Date
                                                                       at java.text.DateFormat.format(DateFormat.java:306)
                                                                       at java.text.Format.format(Format.java:157)

PS:抱歉英语不好

标签: androiddatebuttoncalendar

解决方案


这应该有效:

public class OrderActivity extends AppCompatActivity {

Button dateButton1, dateButton2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_order);

    Date date = new Date();

    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");  

    LocalDateTime today = LocalDateTime.now(); 
    LocalDate tomorrow = LocalDate.now().plusDays(1);

    // LocalDate dayAfterTomorrow = LocalDate.now().plusDays(2);
    // continue like this

    dateButton1 = (Button)findViewById(R.id.button5);
    dateButton2 = (Button)findViewById(R.id.button6);

    dateButton1.setText(dtf.format(now)));
    dateButton2.setText(dtf.format(tomorrow)));
}

}

推荐阅读