32

I want to display the difference between two times in hh:mm format.

The first time is from a database and the second time is the system time. Time difference is updated every second.

How can I do that?

Currently I'm using two manual time if this works perfectly then I implement it into my apps.

public class MainActivity extends Activity 
{
    TextView mytext;
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Timer updateTimer = new Timer();
        updateTimer.schedule(new TimerTask() 
        {
            public void run() 
            {
                try 
                {
                    TextView txtCurrentTime= (TextView)findViewById(R.id.mytext);
                    SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss aa");
                    Date date1 = format.parse("08:00:12 pm");
                    Date date2 = format.parse("05:30:12 pm");
                    long mills = date1.getTime() - date2.getTime();
                    Log.v("Data1", ""+date1.getTime());
                    Log.v("Data2", ""+date2.getTime());
                    int hours = (int) (mills/(1000 * 60 * 60));
                    int mins = (int) (mills % (1000*60*60));

                    String diff = hours + ":" + mins; // updated value every1 second
                    txtCurrentTime.setText(diff);
                } 
                catch (Exception e) 
                {
                    e.printStackTrace();
                }
            }

        }, 0, 1000);
    }
}
Dawid Hyży
  • 3,581
  • 5
  • 26
  • 41
Niks
  • 567
  • 1
  • 6
  • 14

11 Answers11

57

To Calculate the difference between two dates you could try something like:

long millis = date1.getTime() - date2.getTime();
int hours = (int) (millis / (1000 * 60 * 60));
int mins = (int) ((millis / (1000 * 60)) % 60);

String diff = hours + ":" + mins; 

To update the Time Difference every second you can make use of Timer.

Timer updateTimer = new Timer();
updateTimer.schedule(new TimerTask() {
    public void run() {
        try {
            long mills = date1.getTime() - date2.getTime();
                int hours = millis/(1000 * 60 * 60);
                 int mins = (mills/(1000*60)) % 60;

                 String diff = hours + ":" + mins; // updated value every1 second
            } catch (Exception e) {
            e.printStackTrace();
        }
    }

}, 0, 1000); // here 1000 means 1000 mills i.e. 1 second

Edit : Working Code :

public class MainActivity extends Activity {

    private TextView txtCurrentTime;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txtCurrentTime= (TextView)findViewById(R.id.mytext);
        Timer updateTimer = new Timer();
        updateTimer.schedule(new TimerTask() 
        {
            public void run() 
            {
                try 
                {
                    
                    SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss aa");
                    Date date1 = format.parse("08:00:12 pm");
                    Date date2 = format.parse("05:30:12 pm");
                    long mills = date1.getTime() - date2.getTime();
                    Log.v("Data1", ""+date1.getTime());
                    Log.v("Data2", ""+date2.getTime());
                    int hours = (int) (mills/(1000 * 60 * 60));
                    int mins = (int) (mills/(1000*60)) % 60;

                    String diff = hours + ":" + mins; // updated value every1 second
                    txtCurrentTime.setText(diff);
                } 
                catch (Exception e) 
                {
                    e.printStackTrace();
                }
            }

        }, 0, 1000);
    }
Simon.S.A.
  • 6,240
  • 7
  • 22
  • 41
Sanober Malik
  • 2,765
  • 23
  • 30
  • here run method will execute every second, so whatever you want to update or calculate you can write inside it.. – Sanober Malik Mar 12 '13 at 12:09
  • I have checked the code and fixed the problem. Sorry for late reply! Now the code is working. – Sanober Malik Mar 13 '13 at 03:52
  • yaa the code is working perfectly but still it not update every second .. plz try to solve it... – Niks Mar 13 '13 at 06:58
  • i need another favor from you. can you update this code now I need to perform my task with system time and manual time. and then update the difference every second. like System time :- 01:00:00 pm manual time :- 12:50:00 pm ans :- 00:10 when clock reach 01:00:00 pm then 00:11 when clock reach 01:01:00 pm then 00:12 when clock reach 01:02:00 pm and so on plz help – Niks Mar 13 '13 at 07:27
  • let me try again , your code is perfect working for me but i need it to little update. My task is to get the difference between two time 1st time is manual and 2nd time is system time. if i set manual time 12:50:00 pm and system time 01:00:00 pm then i need answer 00:10, after 1 min i need the answer 00:11, and so on . – Niks Mar 13 '13 at 08:56
  • @SanoberMalik Just a little tip: By convention, variable names should start with a lower case character. – Daniel Kvist Mar 03 '15 at 17:27
  • It give some wrong values like I am from India's time is 30 min ahead but it gives -11:-30 – Faizan Haidar Khan Dec 02 '20 at 07:16
10

finally did it yuppiiieee ...

package com.timedynamicllyupdate;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity 
{
    TextView current;
    private TextView txtCurrentTime;
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Thread myThread = null;
        Runnable myRunnableThread = new CountDownRunner();
        myThread= new Thread(myRunnableThread);   
        myThread.start();

        current= (TextView)findViewById(R.id.current);
    }


    public void doWork() 
    {
        runOnUiThread(new Runnable() 
        {
            public void run() 
            {
                try
                {
                    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss aa");

                    txtCurrentTime= (TextView)findViewById(R.id.mytext);

                    Date systemDate = Calendar.getInstance().getTime();
                    String myDate = sdf.format(systemDate);
//                  txtCurrentTime.setText(myDate);

                    Date Date1 = sdf.parse(myDate);
                    Date Date2 = sdf.parse("02:50:00 pm");

                    long millse = Date1.getTime() - Date2.getTime();
                    long mills = Math.abs(millse);

                    int Hours = (int) (mills/(1000 * 60 * 60));
                    int Mins = (int) (mills/(1000*60)) % 60;
                    long Secs = (int) (mills / 1000) % 60;

                    String diff = Hours + ":" + Mins + ":" + Secs; // updated value every1 second
                    current.setText(diff);
                }
                catch (Exception e) 
                {

                }
            }
        });
    }

    class CountDownRunner implements Runnable
    {
        // @Override
        public void run() 
        {
            while(!Thread.currentThread().isInterrupted())
            {
                try 
                {
                    doWork();
                    Thread.sleep(1000); // Pause of 1 Second
                } 
                catch (InterruptedException e) 
                {
                        Thread.currentThread().interrupt();
                }
                catch(Exception e)
                {
                }
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}
Niks
  • 567
  • 1
  • 6
  • 14
7

Using java.time

The modern way is with the java.time classes that supplant the troublesome old date-time classes.

The LocalTime class represents a time-of-day without a date and without a time zone.

Define a formatting pattern with DateTimeFormatter class.

String inputStart = "08:00:12 pm".toUpperCase() ;
String inputStop = "05:30:12 pm".toUpperCase() ;

DateTimeFormatter f = DateTimeFormatter.ofPattern( "hh:mm:ss a" );
LocalTime start = LocalTime.parse( inputStart , f );
LocalTime stop = LocalTime.parse( inputStop , f );

start.toString(): 20:00:12

stop.toString(): 17:30:12

The LocalTime class works within a single generic 24-hour day. So it does not consider crossing midnight. If you want to cross over between days you should be using ZonedDateTime, OffsetDateTime, or LocalDateTime instead, all date-time objects rather than time-of-day-only.

A Duration captures a span of time unattached to the timeline.

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

Calling toString generates text in the standard ISO 8601 format for durations: PnYnMnDTnHnMnS where the P marks the beginning and the T separates the years-months-days from the hours-minutes-seconds. I strongly recommend using this format rather than "HH:MM:SS" format that is ambiguous with clock-time.

If you insist on using the ambiguous clock-time format, in Java 9 and later you can build that string by calling toHoursPart, toMinutesPart, and toSecondsPart.

In your example data we are moving backwards in time, going from 8 PM to 5 PM, so the result is a negative number of hours and minutes, a negative two and a half hours.

d.toString(): PT-2H-30M

See this code run live at IdeOne.com.


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.

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.

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

OK I Build here Funcion for you:

 public void omriFunction(){
    Date Start = null;
    Date End = null;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
    try {
        Start = simpleDateFormat.parse(04+":"+30);
        End = simpleDateFormat.parse(06+":"+45);}
    catch(ParseException e){
        //Some thing if its not working
    }

    long difference = End.getTime() - Start.getTime();
    int days = (int) (difference / (1000*60*60*24));
    int hours = (int) ((difference - (1000*60*60*24*days)) / (1000*60*60));
    int min = (int) (difference - (1000*60*60*24*days) - (1000*60*60*hours)) / (1000*60);
    if(hours < 0){
        hours+=24;
    }if(min < 0){
        float  newone = (float)min/60 ;
        min +=60;
        hours =(int) (hours +newone);}
    String c = hours+":"+min;
    Log.d("ANSWER",c);}

ANSWER :2:15; in the logcat

e-sushi
  • 13,786
  • 10
  • 38
  • 57
2

The process is roughly as follows,

  1. Convert your string instance to a date instance the following way

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    Date date = format.parse("2011-01-03");
    
  2. Assuming the systemTime you have is a long, representing miliseconds since the epoc, you can now do the following

    long difference = longNow - date.getTime();
    int msPerHour = 1000*60*60;
    int hours = difference/secondPerHour;
    int minutes = difference % secondPerHour;
    

    where longNow is your current variable containing system time.

JustDanyul
  • 13,813
  • 7
  • 53
  • 71
  • finally I got it, what I really want to do thanks to every one for your suggestion, code, example and help frndzzzz... – Niks Mar 13 '13 at 09:36
1
Date currentTime = parseDate("11:27:20 AM");
Date endTime = parseDate("10:30:01 AM");

if (endTime.before(currentTime))
{
    Log.e("Time :","===> is before from current time");
}

if (endTime.after(currentTime))
{
    Log.e("Time :","===> is after from current time");
}



private Date parseDate(String date)
{
    String inputFormat = "hh:mm:ss aa";
    SimpleDateFormat inputParser = new SimpleDateFormat(inputFormat, Locale.US);
    try {
        return inputParser.parse(date);
    } catch (java.text.ParseException e) {
        return new Date(0);
    }
}
Coldfin Lab
  • 361
  • 3
  • 8
0

Hi Guys not sure what I was doing wrong , but this helped for me , hope I can help someone else out.

My min were being calculated in some float format so I used this formula

long Min = time %  (1000*60*60)/(60*1000);
time is my date2.getTime() - date1.getTime();

Happy coding

Robert
  • 5,278
  • 43
  • 65
  • 115
DrDroid
  • 1
  • 1
0

Tray The following code to get hour and minute different between two times:

private static int getHoursDiff(Calendar c1, Calendar c2) {
            Date d1 = c1.getTime();
            Date d2 = c2.getTime();
            long mils = d1.getTime() - d2.getTime();
            int hourDiff = (int) (mils / (1000 * 60 * 60));
            return hourDiff;
        }

        private static int getMinuteDiff(Calendar c1, Calendar c2) {
            Date d1 = c1.getTime();
            Date d2 = c2.getTime();
            long mils = d1.getTime() - d2.getTime();
            int minuteFor = (int) (mils / (1000 * 60) % 60);
            return minuteFor;
        } }
Abdurahman Popal
  • 2,859
  • 24
  • 18
0

So I was hunting around for a way where I could get HH/MM/SS from 2 Times in Kolin and this seems like a nice way to do it.

It uses import org.threeten.bp

fun getTimedifference(startTime: LocalDateTime,  endTime: LocalDateTime): String {
        val startTimeInstant = startTime.atOffset(ZoneOffset.UTC).toInstant()
        val endTimeInstant = endTime.atOffset(ZoneOffset.UTC).toInstant()
        val duration = Duration.between(startTimeInstant, endTimeInstant)
        val days = duration.toDays()
        val hours = duration.toHours() - (days * 24)
        val min = duration.toMinutes() - (duration.toHours() * 60)
        val sec = (duration.toMillis() / 1000) - (duration.toMinutes() * 60)
        return "${hours}:${min}:${sec}"
    }
Burf2000
  • 5,001
  • 14
  • 58
  • 117
0

try this function, if you want correct time diff you must add timezone in it, this is a normal mistake.

fun main() {
    val format = "MM/dd/yyyy hh:mm:ss aa"
    val cal = Calendar.getInstance()
    val sdf =  SimpleDateFormat(format, Locale.getDefault())
    sdf.setTimeZone(TimeZone.getTimeZone("Asia/Karachi")) //make sure to set timezone
    
    val arrivedDate = "03/15/2022 12:00:00 PM"
    val currentDate = sdf.format(cal.timeInMillis)
    
    print("Arrived time: " + arrivedDate + "\n")
    print("Current time: " + currentDate + "\n")
    
    val arrivedDateMillis = getLongDateFromString(arrivedDate, sdf) 
    val currentDateMillis = getLongDateFromString(currentDate, sdf)
   
    val diff = (currentDateMillis - arrivedDateMillis) / 1000
    
    val p1 = diff % 60
    var p2 = diff / 60  
    val p3 = p2 % 60
    val p4 = diff / 60 / 60 / 24
    p2 = p2 / 60 % 24

    print("$p4:$p2:$p3:$p1") //days:hours:minutes:seconds
   
}

fun getLongDateFromString(time: String, format: SimpleDateFormat): Long {
    try {
        val date = format.parse(time)
        return date.time

    } catch (e: Exception) {
        e.printStackTrace()
    }
    return 0L
}
Asad
  • 1,241
  • 3
  • 19
  • 32
0

We can also use below options to get the hours and minutes difference between dates

val hours = TimeUnit.MILLISECONDS.toHours(date1.time-date2.time)
val minutes = TimeUnit.MILLISECONDS.toMinutes(date1.time-date2.time)
Sampath Kumar
  • 4,433
  • 2
  • 27
  • 42