我是 android 新手,正在尝试开发一个简单的应用程序,用户将在其中输入两个日期,然后单击一个按钮,他将在几天内收到它们之间的差异。这是我的代码,不幸的是输出始终为 0。
package il.ac.hit.datetodate;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText ed1 = (EditText) findViewById(R.id.editText1);
final EditText ed2 = (EditText) findViewById(R.id.editText2);
final TextView tv = (TextView) findViewById(R.id.textView2);
final Button bt = (Button) findViewById(R.id.button1);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
SimpleDateFormat sdf1 = new SimpleDateFormat("MMM dd yyyy");
SimpleDateFormat sdf2 = new SimpleDateFormat("MMM dd yyyy");
try {
cal1.setTime(sdf1.parse(ed1.getText().toString()));
} catch (ParseException e) {
e.printStackTrace();
}
try {
cal2.setTime(sdf2.parse(ed2.getText().toString()));
} catch (ParseException e) {
e.printStackTrace();
}
long days1 = cal1.getTimeInMillis();
long days2 = cal2.getTimeInMillis();
long diff = (days2 - days1)/(1000*60*60*24);
tv.setText(String.valueOf(diff));
}
});
}
}