0

Well i am trying to define a date and see the difference with recent date in seconds. Below is the code i did inside onCreate method of activity:

    txtNowTime = (TextView)findViewById(R.id.textViewNow);

    SimpleDateFormat formata = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

    String currentDateandTime = formata.format(new Date());

    @SuppressWarnings("deprecation")
    Date oldd = new Date("07/18/2014 11:12:13");
    String olddt_frmt = formata.format(oldd);

    long diff =0;
    try {
          Date d_recent = formata.parse("currentDateandTime");

           diff = d_recent.getTime() - oldd.getTime();


        } catch (ParseException ex) {
             ex.printStackTrace();          }

     txtNowTime.setText(String.valueOf(diff));

But its not showing any result. :-(

shaon007
  • 163
  • 3
  • 16

3 Answers3

1

Change this
Date d_recent = formata.parse("currentDateandTime"); to Date d_recent = formata.parse(currentDateandTime);

Balaji.K
  • 8,745
  • 5
  • 30
  • 39
0

please find the answer

SimpleDateFormat formata = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.getDefault());
String currentDateandTime = formata.format(new Date());
long diff = 0;
try {
Date d_recent = formata.parse(currentDateandTime);
Date olddt_frmt = formata.parse("07/18/2014 11:12:13");
diff = d_recent.getTime() - olddt_frmt.getTime();
} catch (ParseException ex) {
    ex.printStackTrace();
}
User0802
  • 49
  • 1
  • 10
0

See this similar question using Joda-Time. Or use the new java.time package in Java 8. The old java.util.Date and .Calendar class's are notoriously troublesome and should be avoided.

Joda-Time

DateTime then = DateTime.now();
//…
DateTime now = DateTime.now();
Seconds seconds = Seconds.secondsBetween( now, then );
int secondsElapsed = seconds.getSeconds();
Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154