【问题标题】:How to solve this wrong algorithm in DatePicker?如何在 DatePicker 中解决这个错误的算法?
【发布时间】:2018-01-26 09:47:08
【问题描述】:

这是我的问题,每当我在 Date Picker 中选择一个日期时,我的系统都会生成一个特定的日期。这是带有警报对话框的日期选择器的图片:

日期选择器:

具体日期应该是+5天根据你当前的日期,例如。我将在 2018 年 1 月 27 日借一本书。我应该在 2018 年 2 月 1 日之前或等于该日期之前归还它。但我的问题是每当我在 Date Picker 上选择 2018 年 1 月 27 日时。日期搞砸了。我该怎么办?

这是我的程序的代码:

public class Borrow extends AppCompatActivity implements DatePickerDialog.OnDateSetListener{
private FirebaseAuth firebaseAuth;
private DatabaseReference databaseBorrow;
private Button btnBorrow;
public TextView tvScheduleDate,tvSchedule,tvReturnDate;
private int day,month,year,hour,minute;
private int dayFinal,monthFinal,yearFinal,returnDay;
 // private Date date;

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

    firebaseAuth = FirebaseAuth.getInstance();
    if (firebaseAuth.getCurrentUser() == null) {
        finish();
        startActivity(new Intent(this, Login.class));
    }

    Intent intent = getIntent();



    String id = intent.getStringExtra(SearchFragment.BOOK_ID);
    final String bookTitle = intent.getStringExtra(SearchFragment.BOOK_TITLE);
    btnBorrow=(Button)findViewById(R.id.borrowBtn);
    databaseBorrow= FirebaseDatabase.getInstance().getReference("Borrow").child(id);


    btnBorrow.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
         Button();
    }
});

}

private void Button(){

    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
    LayoutInflater inflater = getLayoutInflater();
    View view = inflater.inflate(R.layout.borrow_dialog,(ViewGroup) findViewById(R.id.linearLayout));


    tvScheduleDate = (TextView) view.findViewById(R.id.tvScheduleDate);
    tvReturnDate = (TextView) view.findViewById(R.id.tvReturnDate);
    tvSchedule = (TextView)view.findViewById(R.id.tvSchedule);
    tvSchedule.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view) {
            Calendar c = Calendar.getInstance();

            year = c.get(Calendar.YEAR);
            month = c.get(Calendar.MONTH);
            day = c.get(Calendar.DAY_OF_MONTH);

            DatePickerDialog datePickerDialog = new DatePickerDialog(Borrow.this , Borrow.this , year,month,day);
            datePickerDialog.getDatePicker().setMinDate(c.getTimeInMillis());
            c.add(Calendar.DAY_OF_WEEK,6); //for max date
            datePickerDialog.getDatePicker().setMaxDate(c.getTimeInMillis());
            datePickerDialog.show();
        }
    });

    dialogBuilder.setView(view);
    dialogBuilder.show();
    /*
    String ids = databaseBorrow.push().getKey();
    String buttonText = btnBorrow.getText().toString();
    BorrowBook borrow = new BorrowBook(ids,buttonText,bookTitle,yearFinal,dayFinal,monthFinal);
    databaseBorrow.child(ids).setValue(borrow);
    Toast.makeText(this,"Borrow Successfully",Toast.LENGTH_SHORT).show();*/
}

@Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
        yearFinal = i;
        monthFinal = i1+1;
        dayFinal = i2;


    tvScheduleDate.setText(dayFinal+"-"+monthFinal+"-"+yearFinal);
    // I think I used a wrong algorithm for this one , any suggestions so I 
    can solve this? 
    if(dayFinal>=27) {
        dayFinal=((i2+5)*0+1);
            monthFinal=i1+2;
            tvReturnDate.setText(dayFinal  + "-" + monthFinal + "-" + yearFinal);

    }
}
}

【问题讨论】:

  • '日期搞砸了',你能详细说明一下吗?
  • 例如,我将在 2018 年 1 月 27 日借一个项目。我应该在 2018 年 2 月 1 日归还它。它应该在您当前日期 +5 天。但我的程序生成 2018 年 2 月 32 日 @CowboyFarnz

标签: android date datepicker


【解决方案1】:

你可以这样做

public String getFutureDate(String dt){

    String future_date = "";
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Calendar c = Calendar.getInstance();
    try {
        c.setTime(sdf.parse(dt));
    } catch (ParseException e) {
        e.printStackTrace();
    }
    c.add(Calendar.DATE, 5);  // number of days to add
    SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy");
    future_date = sdf1.format(c.getTime());

    return  future_date;
}

用法

String format_date = yearFinal + "-" + monthFinal  + "-" + dayFinal ;
tvReturnDate.setText(getFutureDate(format_date));

【讨论】:

  • 这是我的最后一个问题,是否可以将此生成的日期存储在数据库中?例如,我想将其存储在 firebase 数据库中?
  • 是的,当然,定义全局字符串fut_date;然后通过 fut_date = getFutureDate(format_date) 获取它,您可以在 Activity 中的任何位置使用
【解决方案2】:

将全局变量声明到您的活动类中:

private Button mPickDate;
private int mYear;
private int mMonth;
private int mDay;
static final int DATE_DIALOG_ID = 0;

将此代码写入 onCreate() 函数:

//date picker presentation
    mPickDate = (Button) findViewById(R.id.pickDate);//button for showing date picker dialog 
    mPickDate.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) { showDialog(DATE_DIALOG_ID); }
    });

// get the current date
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);


// display the current date
updateDisplay();

在 onCreate() 函数之外写下这些函数:

//return date picker dialog
@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DATE_DIALOG_ID:
        return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay);
    }
    return null;
}

//update month day year
private void updateDisplay() {
    mBodyText.setText(//this is the edit text where you want to show the selected date
        new StringBuilder()
            // Month is 0 based so add 1
        .append(mYear).append("-")
        .append(mMonth + 1).append("-")
        .append(mDay).append(""));


            //.append(mMonth + 1).append("-")
            //.append(mDay).append("-")
            //.append(mYear).append(" "));
}

// the call back received when the user "sets" the date in the dialog
private DatePickerDialog.OnDateSetListener mDateSetListener =
    new DatePickerDialog.OnDateSetListener() {
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            mYear = year;
            mMonth = monthOfYear;
            mDay = dayOfMonth;
            updateDisplay();
        }
};

【讨论】:

    猜你喜欢
    • 2015-12-25
    • 2021-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多