【问题标题】:Is there another way to add days in android calendar picker [duplicate]是否有另一种方法可以在 android 日历选择器中添加日期 [重复]
【发布时间】:2019-07-25 03:39:10
【问题描述】:

我正在尝试添加超过一个月天数的天数。例如 2019 年 7 月 1 日,我加上 32 天,结果将是 2019 年 8 月 2 日。

SimpleDateFormat format = new SimpleDateFormat("mm/dd/yyy");
SimpleDateFormat Dateformat = new SimpleDateFormat("mm/dd/yyy");
String getDate = date_pick.getText().toString();
Date mDate;
Date result_desu;
try {
    mDate = format.parse(getDate);
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(mDate);
    calendar.add(Calendar.DATE, 32);
    String formattedDate = Dateformat.format(calendar.getTime());
    date_result.setText(formattedDate);    // format output
} catch (ParseException e) {
    e.printStackTrace();
}

我一直在使用此代码,但事实证明仅使用同一月份重置日期示例:2019 年 7 月 1 日;结果:2019 年 7 月 2 日。

【问题讨论】:

  • 顺便考虑扔掉长期过时且臭名昭著的麻烦SimpleDateFormat和朋友,并将ThreeTenABP添加到您的Android项目中,以便使用java.time,现代Java日期和时间API .使用起来感觉好多了。
  • 您应该使用 LocalDate::plusDays 而不是问题中看到的可怕的旧日期时间类。

标签: java android date android-calendar days


【解决方案1】:

试试这个:

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.text.ParseException;
class Main{
   public static void main(String args[]){
    String oldDate = "2019-07-1";  
    System.out.println("Date before Addition: "+oldDate);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Calendar c = Calendar.getInstance();
    try{
       c.setTime(sdf.parse(oldDate));
    }catch(ParseException e){
        e.printStackTrace();
     }

    c.add(Calendar.DAY_OF_MONTH, 32);  
    String newDate = sdf.format(c.getTime());  
    System.out.println("Date after Addition: "+newDate);
   }
}

输出:

Date before Addition: 2019-07-1
Date after Addition: 2019-08-02

【讨论】:

  • 乐于助人:)
  • 如果您 (1) 解释您的代码如何解决提问者的问题 (2) 使用现代 Java 日期和时间 API 展示解决方案,或者至少提及SimpleDateFormatCalendar 陈旧且设计不佳,还有更好的选择。
  • 这些可怕的日期时间类在几年前被 JSR 310 定义的现代 java.time 类所取代。
猜你喜欢
  • 1970-01-01
  • 2014-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-05
  • 2020-03-17
  • 1970-01-01
相关资源
最近更新 更多