场景
用户可以使用该应用程序记录许可证,他们可以输入兑换许可证的日期,还可以输入许可证的长度(天)。
我正在尝试确定您是否能够从这两个变量中计算出一个新日期。例如
days = INPUT FROM USER; days = 7;
dateRedeemed = new Date(); date = 24/06/2019;
newDate = dateRedeemed + days; newDate = 01/07/2019;
//Getting the values
String name = txtName.getText();
String contact = txtContact.getText();
int years = Integer.parseInt(cboyears.getSelectedItem().toString());
int months = Integer.parseInt(cboMonths.getSelectedItem().toString());
int days = Integer.parseInt(cboDays.getSelectedItem().toString());
//Calculation
days = (years * 365) + (months * 12) + days;
SimpleDateFormat format = new SimpleDateFormat("dd/MM/YYYY");
Date dRedeemed = cboDate.getDate();
String strRedeemed = format.format(dRedeemed);
如果有谁能帮助的话,那会很棒
修改
此线程中的一些很好的建议,很多人已经指出Date类非常糟糕且过时了,我现在将开始使用 LocalDateTime 类,因为它似乎更强大,我想问的另一件事是,有一个更有效的日期选择器。我一直在使用swingx日期选择器,还有更有效的选择吗?
答案 0 :(得分:3)
Java(任何)解决方案:
Date currentDate = new Date(); // or any date you set
Calendar c = Calendar.getInstance();
c.setTime(currentDate);
c.add(Calendar.DAY_OF_MONTH, 7);
Date currentDatePlusSevenDays = c.getTime();
Java 8+解决方案:
Date currentDate = new Date(); // or any date you set
LocalDateTime localDateTime = currentDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
localDateTime = localDateTime.plusDays(7);
Date currentDatePlusSevenDays = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
带有外部库Joda-Time的Java(任何)解决方案:
DateTime currentDate = DateTime.now(); // or any date you set
DateTime currentDatePlusSevenDays = currentDate.plusDays(7);
答案 1 :(得分:0)
如果使用Java 8,则应使用LocalDateTime类。
它使事情变得容易得多。
LocalDateTime dateRedeemed = LocalDateTime.now(); // 2019-06-24T16:31:16.993
// custom date also possible (year, month, day (of month), hours, minutes, seconds and nanoseconds)
LocalDateTime dateRedeemed = LocalDateTime.of(2019, 06, 24, 13, 55, 36, 123);
// Add 7 days
LocalDateTime newDate = dateRedeemed.plusDays(7);
System.out.println(newDate.toString()); // 2019-07-01T16:31:16.993
答案 2 :(得分:0)
如果您不使用Java 8,则可以使用以下代码
int days = 8;
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.DATE, days);
SimpleDateFormat format = new SimpleDateFormat("dd/MM/YYYY");
Date newDate = c.getTime();
System.out.println(dateFormat.format(newDate));