gpt4 book ai didi

android - 如何根据日期变化计算两个时间字段之间的时间差

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:20:06 24 4
gpt4 key购买 nike

我想计算时差。我有三个 EditTexts ,我想在前两个 edittexts 中以 HH:MM 格式输入时间。然后计算时间差,结果将以相同的格式显示在第三个编辑文本字段中。如果日期发生变化,则按时差计算,即

如果第一次 = 23:00 第二次 = 01:00

那么,时差=02:00

public class TimeCalculate extends Activity {

private String mBlock;
private String mBlockoff;
private String mBlockon ;

// String mHours, mMinutes;

Date date1, date2;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditText blockoff = (EditText) findViewById(R.id.blockoff);
mBlockoff = blockoff.getText().toString();

EditText blockon = (EditText) findViewById(R.id.blockon);
mBlockon = blockon.getText().toString();

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm");

try {
date1 = simpleDateFormat.parse(mBlockoff);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
date2 = simpleDateFormat.parse(mBlockon);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mBlock = getDifference(date1, date2);
EditText block = (EditText) findViewById(R.id.block);
block.setText(mBlock.toString());

}
public static String getDifference(Date startTime, Date endTime) {

if (startTime == null)
return "corrupted";
Calendar startDateTime = Calendar.getInstance();
startDateTime.setTime(startTime);
Calendar endDateTime = Calendar.getInstance();
endDateTime.setTime(endTime);
long milliseconds1 = startDateTime.getTimeInMillis();
long milliseconds2 = endDateTime.getTimeInMillis();
long diff = milliseconds2 - milliseconds1;
/*int hours = (int)diff / (60 * 60 * 1000);
int minutes = (int) (diff / (60 * 1000)); minutes = minutes - 60 * hours;
long seconds = diff / (1000); */
//timeDiff = DateUtils.formatElapsedTime(seconds);

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:MM");
Date date = new Date(diff);
return simpleDateFormat.format(date);

}

}

我执行了这段代码,但给出了错误,因为找不到源。我认为 getDifference 方法有错误。请给出任何其他逻辑

最佳答案

时差由以下代码计算:

long difference = date2.getTime() - date1.getTime(); 
days = (int) (difference / (1000*60*60*24));
hours = (int) ((difference - (1000*60*60*24*days)) / (1000*60*60));
min = (int) (difference - (1000*60*60*24*days) - (1000*60*60*hours)) / (1000*60);

编辑:

date1 和 date2 是 Date 对象,如果你有 EditText 那么你可以使用下面的代码将你的文本转换成 Date 对象,

  DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); // Make sure user insert date into edittext in this format.
Date dateObject;

try{
String dob=(tx.getText().toString());
dateObject = formatter.parse(dob);
date = new SimpleDateFormat("dd/MM/yyyy").format(dateObject);

}

关于android - 如何根据日期变化计算两个时间字段之间的时间差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5172593/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com