Getting Time Difference In android from Timestamp - android

I am saving current date in timestamp value in my firebase with below code
userValues.put("p_date", ServerValue.TIMESTAMP);
what I need to do is show a time difference between above saved value and current timestamp value, I have tried below code
//time ago
String starttime = book.getP_date().toString(); //getting saved timestamp from firebase
//current time
Long tsLong = System.currentTimeMillis()/1000;
String endtime = tsLong.toString();
long diffTime = Long.parseLong(endtime) - Long.parseLong(starttime);
String elapsedtime = new SimpleDateFormat("hh:mm:ss").format(Long.parseLong(String.valueOf(diffTime)));
tvTimeAgo.setText(elapsedtime+"ago");
it is giving a result like 07:59:56 ago shown time difference is returning wrong result also what I need to have is 0h 5min 3s ago
how can I achieve this?

You can use TimeUnit.MILLISECONDS for formate TimeStamp as below
String timeHH_MM_SS = String.format("%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(diffTime),
TimeUnit.MILLISECONDS.toMinutes(diffTime) % TimeUnit.HOURS.toMinutes(1),
TimeUnit.MILLISECONDS.toSeconds(diffTime) % TimeUnit.MINUTES.toSeconds(1));
tvTimeAgo.setText("Time in hh:mm:ss is: "+timeHH_MM_SS);

Related

Difference between two Times in Minutes are coming as negative

I have a method which takes two String parameters. the two strings are Time values in 24 hour format. The Times are picked using a TimePicker from UI.
The goal of the method is to get the duration between the StartTime and EndTime in Minutes.
public static String getTimeDuration(String StartTime24, String EndTime24)
{
String duration = "";
try
{
SimpleDateFormat parseFormat = new SimpleDateFormat("HH:mm");
Date startTime = parseFormat.parse(StartTime24);
Date endTime = parseFormat.parse(EndTime24);
long mills = endTime.getTime() - startTime.getTime();
long minutes = mills/(1000 * 60);
duration = "(" + minutes + " Minutes)";
}
catch(ParseException ex)
{
// exception handling here
}
return duration;
}
The method works fine if both the times are within a Single Date. For example:
StartTime = 22:15
EndTime = 23:51
Output = (96 Minutes)
But my problem is, the method returns negative if the end time is after 12'o clock at night. For example,
StartTime = 23:51
EndTime = 0:55
Output = (-1376 Minutes)
What I want: (64 Minutes)
How can get the duration correct ?
As there is no date used, you have to check first if your endTime is less than your startTime. If yes, then your endTime is on the next day and you have to add 1 day/86 400 000 milliseconds. Then you will have your desired result.
Just add this condition:
if(endTime.getTime() < startTime.getTime()){
long mills = ((endTime.getTime() + 86400000) - startTime.getTime()); 1 day = 86 400 000 mill
}
Hope this helps
You're only parsing the minutes and hours. There's no day on there. So that puts both times on the same day (the first day of the epoch, Jan 1 1970 to be exact). So the answer is correct. If you want it to treat the end time as the next day if its earlier than the start time, then add 1 day to the result (1440 minutes) if the result is less than 0.

How to calculate elapsed time and date in android

I want my app to show the time elapsed from the point an entry was stored in the database to the point it is fetched from the database.
I am currently doing something like this which gives me time elapsed in seconds:
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss aa");
Date systemDate = Calendar.getInstance().getTime();
String myDate = sdf.format(systemDate);
Date Date1 = sdf.parse(myDate);
Date Date2 = sdf.parse(savedDate);
int dateDiff = getTimeRemaining();
long millse = Date1.getTime() - Date2.getTime();
long mills = Math.abs(millse);
long Mins = mills/(1000*60);
String diff = +dateDiff+ "days " + Mins+ " mins";
cal[1] = "" +Mins;
t3.setText(diff);
But I also want it to include the no of days since the data was stored. As of now, it resets when the day is over. I want it to give me the total minutes after N days. How should I do it? Thanks in advance.
You firstly need to determine the number of seconds from database-stored-time until now.
long ageOfDatabaseEntry = (System.currentTimeMillis() - databaseEnteredTimeMillis)
You then need to determine how many days you want, then modulo the age by that number to get the remaining number of milliseconds.
long getRemainingMinutes(long age, int days) {
// Use the modulus operator to get the remainder of the age and days
long remainder = age % (days * 86400000);
if(remainder == age) {
throw new InvalidArgumentException("The number of days required exceeds the age of the database entry. Handle this properly.");
}
// Turn the remainder in milliseconds into minutes and return it
return remainder / 60000;
}

Determining if a time is between two other times

I am trying to take hours that I've parsed using SimpleDateFormat and determining whether or not the current time is between the two sets of hours. Basically, given a place's hours, I'm trying to determine if it is currently open our closed.
I am getting the current time by doing the following:
SimpleDateFormat sdf2 = new SimpleDateFormat("kk:mm");
Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR);
int minute = now.get(Calendar.MINUTE);
String currentHour = Integer.toString(hour);
String currentMinute = Integer.toString(minute);
String timeNow = currentHour + ":" + currentMinute;
Date timeRightNow = sdf2.parse(timeNow);
Then, I determine whether timeRightNow is between the opening and closing times, I am doing the following:
if (timeOpen.before(timeRightNow) && timeClose.after(timeRightNow)) {
openStatus = "open!";
} else {
openStatus = "closed.";
}
Both timeOpen and timeClose are found by parsing a String using sdf2 in the exact same way as timeRightNow is found.
Every time that this runs, it sets openStatus to "closed." even when the current time is between the open and close times. Can anyone point me in the right direction to figure out why this is happening?
I changed Calendar.HOUR to Calendar.HOUR_OF_DAY. This resolved the issue.

Android Date difference return in minutes

I am getting UTC date from db. And subtracting that from current utc DateTime. I would like to have diff. in minutes. Something in not quite right.
Date currenttimedate = DateTime.UTCNow();
String lastsynctime = c.getString(c.getColumnIndex(columnname)).toString();
Date lastruntimedate = DateTime.StringDateToDate(lastsynctime, "MM/dd/yyyy HH:mm:ss");
long diffInMs = (currenttimedate. getTime() - lastruntimedate.getTime());
// convert it to Minutes
long diffInMins = TimeUnit.MILLISECONDS.toMinutes(diffInMs);
// return time in minutes
response = (int)(diffInMins);
It's returning something like 720 minutes. Expected answer can not be more than 5. As data is synced every 5 mins.

How to compare two timestamps in android?

I want to compare two timestamps and if the difference of that is (-+5minuts) then I want to display alert dialog.
i.e. If currently in our watch 4PM the second time is 4.05PM or 3.55PM then alert will display else not.
Can anyone suggest me the way how can I get the solution of this.??
I found after search the function of getting timeStamp and how to compare two timestamps but for this type of condition is there any method or function?
Thanks.
My code is:-
date= new Date();
currentTime = date.getTime();
if(currentTime !=0 && previousTime !=0){
String result = (String) DateUtils.getRelativeTimeSpanString(currentTime, previousTime, 0);
}
And I am storeing current time in to previous time lilke tis way :-
if(currentTime != previousTime){
previousTime = currentTime;
}
There's two approaches you could take, depending on whether you just want to measure time elapsed, or want to set future times to compare to.
The first is similar to Sourabh Saldi's answer, record the result from
long prevEventTime = System.currentTimeMillis();
then compare it with System.currentTimeMillis() until the difference is more than 300000
As you have mentioned, your timestamp from the server is in milliseconds since January the 1st, 1970. This means it is directly comparable to System.currentTimeMillis(). As such, use:
long serverTimeStamp=//whatever your server timestamp is, however you are getting it.
//You may have to use Long.parseLong(serverTimestampString) to convert it from a string
//3000(millliseconds in a second)*60(seconds in a minute)*5(number of minutes)=300000
if (Math.abs(serverTimeStamp-System.currentTimeMillis())>300000){
//server timestamp is within 5 minutes of current system time
} else {
//server is not within 5 minutes of current system time
}
The other method looks closer to what you're already doing - using the Date class to store the current and compared time. To use these, you'll want to be using the GregorianCalendar class to handle them. Calling
calendar=new GregorianCalendar();
will create a new calendar, and automatically set it's date to the current system time. You can also use all the functions supplied in the GregorianCalendar class to roll the time forward or backward using something of the form
calendar.add(GregorianCalendar.MINUTE, 5);
or set it to a Date object's time with
calendar.setTime(date);
In your case, depending on how much flexibility you want both the GregorianCalendar class and the Date class have after() methods, so you probably want something like the following:
Create somewhere:
Date currentDate=newDate();
Then set your alarm point:
calendar=new GregorianCalendar(); //this initialises to the current system time
calendar.setTimeInMillis(<server timestamp>); //change to whatever the long timestamp value from your server is
calendar.add(GregorianCalendar.MINUTE, 5); //set a time 5 minutes after the timestamp
Date beforeThisDate = calendar.getTime();
calendar.add(GregorianCalendar.MINUTE, -10); //set a time 5 minutes before the timestamp
Date afterThisDate = calendar.getTime();
Then check if the current time is past the set alarm point with
currentDate.setTime(System.currentTimeMillis());
if ((currentDate.before(beforeThisDate))&&(currentDate.after(afterThisDate))){
//do stuff, current time is within the two dates (5 mins either side of the server timestamp)
} else {
//current time is not within the two dates
}
This approach can seem a bit more long winded, but you'll find it is very robust and flexible, and can easily be extended to set alarm points far in the future, or use the GregorianCalendar methods to easily set dates hours, days or weeks into the future.
How about just:
private static final long FIVE_MINUTES = 1000 * 60 * 5; //5 minutes in milliseconds
long currentTime = new Date().getTime();
long previousTime = mPreviousTime;
long differ = (currentTime - previousTime);
if (differ < FIVE_MINUTES && differ > -FIVE_MINUTES ){
// under +/-5 minutes, do the work
}else{
// over 5 minutes
}
long etime = 0;
final long time1 = uptimeMillis();
/* do something */
final long time2 = uptimeMillis();
if (time2 < time1) {
etime = Long.MAX_VALUE - time1 + time2;
} else {
etime = time2 - time1;
}
then check this etime and do as required!!1
Use this following method to change your dates in epoch format
public Long getChnagedDate(Activity act,String date) throws ParseException
{
long epoch = new java.text.SimpleDateFormat ("MM/dd/yyyy HH:mm:ss aa").parse(date).getTime();
return epoch/1000;
}
and after check the difference in http://www.epochconverter.com.
Hope it helps you.
Joda time will help you with this task.
import org.joda.time.Interval;
http://joda-time.sourceforge.net/

Categories

Resources