1

I want to find difference between current system time and inserted data&time String. I have tried this:

 try {

            String strFileDate = "2012-04-19 15:15:00";
            DateFormat formatter2 = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
            Date date = formatter2.parse(strFileDate);
            long difference = date.getTime() - System.currentTimeMillis();
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(difference);
            Toast.makeText(getBaseContext(),
                    formatter2.format(calendar.getTime()), Toast.LENGTH_LONG)
                    .show();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 

but it does not give me the right result. Am I doing it right?

Update

I tried following ::

String strFileDate = "2012-04-19 15:15:00";
            DateFormat formatter2 = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
            Date date = formatter2.parse(strFileDate);
            long diffInMs = date.getTime()
                    - new Date(System.currentTimeMillis()).getTime();

            long diffInSec = TimeUnit.MILLISECONDS.toSeconds(diffInMs);

            long hour = diffInSec / (1000 * 60 * 60);
            double minutes = diffInSec / (1000 * 60);
            // long diffInHour = TimeUnit.to(diffInMs);

            Toast.makeText(getBaseContext(),
                    "left time is :: " + hour + ":" + minutes,
                    Toast.LENGTH_LONG).show();

output:: left time is:: -2 : -131.0

UPdate(20/4/2012)

try {
            Date dt = new Date();
            String strFileDate = "2012-04-20 13:10:00";
            DateFormat formatter2 = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
            Date date = formatter2.parse(strFileDate);
            String s = getTimeDiff(dt, date);
            Log.i("Date is :: >>> ", s);
        } catch (Exception e) {
            e.printStackTrace();
        }
 public String getTimeDiff(Date dateOne, Date dateTwo) {
        String diff = "";
        long timeDiff = Math.abs(dateOne.getTime() - dateTwo.getTime());
        diff = String.format("%d hour(s) %d min(s)", TimeUnit.MILLISECONDS.toHours(timeDiff),
                TimeUnit.MILLISECONDS.toMinutes(timeDiff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDiff)));
        return diff;

}

Output:: 04-20 12:48:06.629: INFO/Date is :: >>>(1295): 2183 hour(s) 38 min(s)

Ron
  • 24,175
  • 8
  • 56
  • 97
user1343673
  • 241
  • 1
  • 4
  • 10
  • i want time differance in minut and hour.. – user1343673 Apr 19 '12 at 10:22
  • What is not working? What are you expecting to see in the Toast? What do you expect from this snippet? Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(difference); Please give more details. – krishnakumarp Apr 19 '12 at 10:26
  • Checkout this question. http://stackoverflow.com/questions/635935/how-can-i-calculate-a-time-span-in-java-and-format-the-output – krishnakumarp Apr 19 '12 at 10:28
  • @krishnakumarp i have update my code please check it – user1343673 Apr 19 '12 at 11:50
  • you should replace long diffInMs = date.getTime() - new Date(System.currentTimeMillis()).getTime(); with long diffInMs = new Date(System.currentTimeMillis()).getTime() - date.getTime(); – krishnakumarp Apr 20 '12 at 03:40
  • FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/9/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/9/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [java.time](https://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes built into Java 8 & Java 9. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Feb 28 '18 at 21:38

5 Answers5

5
String strFileDate = "2012-04-19 15:15:00";
DateFormat formatter2 = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
Date date = formatter2.parse(strFileDate);
long diffInMs = date.getTime() - new Date(System.currentTimeMillis()).getTime();


long diffInSec = TimeUnit.MILLISECONDS.toSeconds(diffInMis);

long diffInHour = TimeUnit.MILLISECONDS.toHours(diffInMis);

use TimeUnit to get the number of seconds. http://developer.android.com/reference/java/util/concurrent/TimeUnit.html

Edited:

Get TIMEUNIT Code here

public String getTimeDiff(Date dateOne, Date dateTwo) {
        String diff = "";
        long timeDiff = Math.abs(dateOne.getTime() - dateTwo.getTime());
        diff = String.format("%d hour(s) %d min(s)", TimeUnit.MILLISECONDS.toHours(timeDiff),
                TimeUnit.MILLISECONDS.toMinutes(timeDiff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDiff)));
        return diff;
}
Mohammed Azharuddin Shaikh
  • 41,633
  • 14
  • 96
  • 115
1

Use JodaTime for calculating period(Time Difference). http://joda-time.sourceforge.net/

Shaiful
  • 5,643
  • 5
  • 38
  • 41
  • Then use the simple calculation. If you want the difference in day, month, year, minute, second then you need JodaTime. – Shaiful Apr 19 '12 at 10:23
  • FYI, the [*Joda-Time*](http://www.joda.org/joda-time/) project is now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), with the team advising migration to the [java.time](http://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Feb 28 '18 at 21:39
1
    Calendar calendar = Calendar.getInstance();
calendar.setTime(date.getYear(),date.getMonth(),date.getDay(),date.getHourOFday(),date.getMinutes(),date.getSeconds); // not syntactically right..
long difference = System.currentTimeMillis()-calendar.getTimeInMillis();

and for getting difference in hour

double hour = difference/(1000*60*60);
double minutes = difference/(1000*60);
ngesh
  • 13,398
  • 4
  • 44
  • 60
0
  • What output do you get?
  • What output do you expect?

See #3960661 if you need this time in seconds.

Community
  • 1
  • 1
shkschneider
  • 17,833
  • 13
  • 59
  • 112
  • Then look at [#6118922](http://stackoverflow.com/questions/6118922/convert-seconds-value-to-hours-minutes-seconds-android-java) :) – shkschneider Apr 19 '12 at 10:23
  • @PareshMayani .. is there something you even tolerate.. why do you make fun of people who ask amature questions... i bet if you had spent the same amount of time answering someone's question it would have helped them,.. rather than trying to be funny here.. 2nd time same **BMW** comment.. what a shame... – ngesh Apr 19 '12 at 12:14
  • @sandy FYI, At this point of time, there are lot many questions/answers already available here for the topic "Date/time difference". And he directly saying in "order" like language that i want this, this. – Paresh Mayani Apr 19 '12 at 12:17
  • @PareshMayani .. why don't you paste a link then... why do you always crack jokes... it discourages anyone from asking question.. – ngesh Apr 19 '12 at 12:18
0

tl;dr

ChronoUnit.MINUTES.between(
    LocalDateTime.parse( "2012-04-19 15:15:00".replace( " " , "T" ) ).atZone( ZoneId.of( "Pacific/Auckland" ) ) ,
    LocalDateTime.parse( "2012-04-19 23:49:00".replace( " " , "T" ) ).atZone( ZoneId.of( "Pacific/Auckland" ) ) 
)

514

Time zone

Your code ignores the crucial issue of time zone.

The java.util.Date class represents a moment in UTC. Meanwhile, your input string "2012-04-19 15:15:00" lacks any indicator of time zone or offset-from-UTC. You must explicitly place that value into the context of an expected/desired zone/offset or else those legacy classes will apply a zone/offset implicitly.

java.time

The modern approach uses the java.time classes built into Java 8 and later.

Your input nearly complies with standard ISO 8601 formatting. Switch that SPACE in the middle for a T.

String input = "2012-04-19 15:15:00".replace( " " , "T" ) ;  // Convert to ISO 8601 format.

Parse as a LocalDateTime object, as your input lacks a zone or offset.

LocalDateTime ldt = LocalDateTime.parse( input ) ;

Apply the zone or offset that you know for certain was intended for that input.

OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC ) ; // Or some other offset.

…or…

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;

If you want the delta between two moments as a span of time unattached to the timeline scaled as hours-minutes-seconds, calculate a Duration.

Duration d = Duration.between( start , stop ) ;

Similar, but scaled in years-months-days, use Period. Extract LocalDate date-only objects to feed the factory method of Period.

Period p = Period.between( start.toLocalDate() , stop.toLocalDate() ) ;

Total elapsed

If you want a single number of total elapsed minutes, seconds, etc., use ChronoUnit::between method on the ChronoUnit enum.

long totalMinutes = ChronoUnit.MINUTES.between( start , stop ) ;  // Calculate total number of minutes in entire span of time.

Generating strings

Generate a string in standard ISO 8601 format. Just call Duration::toString or Period::toString.

The format is PnYnMnDTnHnMnS where P marks the beginning, and T separates any years-months-days from any hours-minutes-seconds.

String output = d.toString() ;

You can interrogate for the parts by calling various getter methods.

Tip: If you work with such spans of time much at all, add the ThreeTen-Extra library to your project to use the Interval and LocalDateRange classes.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154