我有兩個名爲clockedin和clockedout的字符串變量。我把它們放在共享首選項中,現在我試圖調用它們並將它們轉換爲整數,這樣我就可以在時鐘的時間內減去超時的時間以查看工作了多少個小時。減去兩個時間字符串
public void onCheckedChanged(CompoundButton compoundButton, boolean b){
if(b){
Calendar c = Calendar.getInstance();
System.out.println(c.getTime());
SimpleDateFormat df = new SimpleDateFormat("hh:mm a");
String formattedDate = df.format(c.getTime());
TextView clockedin = (TextView)findViewById(R.id.clockedin);
clockedin.setText(formattedDate);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("toggleButton", tb.isChecked());
editor.commit();
SharedPreferences sharedPreferences2=getSharedPreferences("MyData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor1= sharedPreferences2.edit();
editor1.putString("clockedin", formattedDate);
editor1.commit();
}
else {
Calendar c = Calendar.getInstance();
System.out.println(c.getTime());
SimpleDateFormat df = new SimpleDateFormat("hh:mm a");
String formattedDate = df.format(c.getTime());
TextView clockedout = (TextView)findViewById(R.id.clockedout);
clockedout.setText(formattedDate);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("toggleButton", false);
editor.commit();
SharedPreferences sharedPreferences2=getSharedPreferences("MyData2", Context.MODE_PRIVATE);
SharedPreferences.Editor editor1= sharedPreferences2.edit();
editor1.putString("clockedout", clockedout.getText().toString());
editor1.commit();
SharedPreferences sharedPreferences1 = getSharedPreferences("MyData", Context.MODE_PRIVATE);
String clockedin =sharedPreferences1.getString("clockedin", DEFAULT);
}}
我的轉換方法:
public void onClickButtonListener2(){
Button button2;
button2 = (Button) findViewById(R.id.calctotal);
button2.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Date date = null;
Date date2 = null;
SharedPreferences sharedPreferences1 = getSharedPreferences("MyData", Context.MODE_PRIVATE);
String clockedin =sharedPreferences1.getString("clockedin", DEFAULT);
SharedPreferences sharedPreferences2 = getSharedPreferences("MyData2", Context.MODE_PRIVATE);
String clockedout =sharedPreferences2.getString("clockedout",DEFAULT);
DateFormat outFormat = new SimpleDateFormat("hh:mm");
try {
date = outFormat.parse(String.valueOf(clockedout));
date2 = outFormat.parse(clockedin);
}catch (ParseException e){
e.printStackTrace();
}
if (date2.before(date)){
long diffMs = date.getTime() - date2.getTime();
long diffSec = diffMs/1000;
long min = diffSec/60;
double hour = (double)min/60;
double hourA = Math.round(hour *100.0)/100.0;
TextView totalhours=(TextView)findViewById(R.id.totalhours);
totalhours.setText((int) hourA);
}
}
});
}
我的日誌attatched enter image description here
你剛纔不是問這個約5小時前? – ctst
是的,但現在我有日誌 – user4792835