1

I'm trying to make an app, where the user must input date and a system will show how much time has passed after that. But It gives me wrong time. When I input my date and press the button, it shows me: 19/06/1989 21:39:32

Here is the code:

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();
}

Where's the mistake in my code?

Ziezi
  • 6,375
  • 3
  • 39
  • 49
  • 2
    Why are you displaying a formatted date if you want to show the user how much time has passed since their input date? – CubeJockey Sep 21 '15 at 20:19
  • Check this answer out http://stackoverflow.com/a/25355659/2350083 for how to format the difference between two dates. – Jon Sep 21 '15 at 20:59

1 Answers1

0

Your assumption is wrong. You cannot subtract two dates and expect date. Your "diff" is some time period. You have to manually transform it to years, months, days etc. (or use some third libraries).

borysfan
  • 182
  • 1
  • 6