shaon007
shaon007

Reputation: 163

How can i calculate difference in seocnds between a predefined date time and recent date time

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. :-(

Upvotes: 0

Views: 54

Answers (3)

Basil Bourque
Basil Bourque

Reputation: 339332

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

Upvotes: 0

User0802
User0802

Reputation: 49

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

Upvotes: 0

Balaji.K
Balaji.K

Reputation: 4829

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

Upvotes: 1

Related Questions