android - 我如何将日期有序地放在每个按钮上?
问题描述
我有 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:抱歉英语不好
解决方案
这应该有效:
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)));
}
}
推荐阅读
- python - Apache Airflow - 在 dag 和日期更改的每个任务中重新运行 Prescript
- java - 无法识别 ADB 命令
- javascript - 如何仅允许文本字段使用字母,验证“OnClick”事件?请纠正我我的脚本做错了什么
- r - R中的情节忽略了看起来像日期的字符串的自定义刻度线?
- elasticsearch - 在 wordlist 上实施 Google 自定义搜索
- mysql - 从表中选择查询并加上表名作为列
- directus - Directus 多对多返回反转数据
- go - Google Cloud Functions 的供应商依赖项是否有性能优势?
- javascript - 密码验证正则表达式之外的数字或特殊字符要求
- php - 点击提交后如何将数据插入数据库?