gpt4 book ai didi

java - 查找用户输入的当前日期和时间之间的差异

转载 作者:太空宇宙 更新时间:2023-11-04 13:25:35 28 4
gpt4 key购买 nike

我正在尝试制作一个应用程序,用户必须输入日期,系统将显示此后已经过去了多少时间。但这给了我错误的时间。当我输入日期并按下按钮时,它会显示:19/06/1989 21:39:32

这是代码:

Calendar sd = Calendar.getInstance();
TextView tv;
EditText year,month,day,hour,minute,second;
Button button2;
int y,m,d,h,min,s;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test7);
tv = (TextView)findViewById(R.id.textView4);
year = (EditText)findViewById(R.id.year);
month = (EditText)findViewById(R.id.month);
day = (EditText)findViewById(R.id.day);
hour = (EditText)findViewById(R.id.hour);
minute = (EditText)findViewById(R.id.minute);
second = (EditText)findViewById(R.id.second);
button2 = (Button)findViewById(R.id.button2);
button2.setOnClickListener(this);

}
public void onClick(View v) {
y = Integer.parseInt(year.getText().toString());
m = Integer.parseInt(month.getText().toString());
d = Integer.parseInt(day.getText().toString());
h = Integer.parseInt(hour.getText().toString());
min = Integer.parseInt(minute.getText().toString());
s = Integer.parseInt(second.getText().toString());
sd.set(Calendar.YEAR,y);
sd.set(Calendar.MONTH,m-1);
sd.set(Calendar.DAY_OF_MONTH,d);
sd.set(Calendar.HOUR_OF_DAY,h);
sd.set(Calendar.MINUTE,min);
sd.set(Calendar.SECOND,s);
final Runnable refresh = new Runnable() {

@Override
public void run() {
long yourmilliseconds = System.currentTimeMillis();
long diff = yourmilliseconds - sd.getTimeInMillis();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date resultdate = new Date(diff);
tv.setText("" + sdf.format(resultdate));
}
};


Thread updateThread = new Thread() {
@Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(refresh);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
updateThread.start();
}

我的代码哪里出了问题?

最佳答案

你的假设是错误的。您不能减去两个日期并期望日期。你的“差异”是某个时间段。您必须手动将其转换为年、月、日等(或使用一些第三方库)。

关于java - 查找用户输入的当前日期和时间之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32703820/

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