Chronometer set wrong long value - android

Set manually long value to chronometer.my long value is correct but when I set this to chronometer.setBase()it display specially character instead of correct time.
// hourInt = 4
// minInt = 34
// secInt = 40
Calendar cal1 = Calendar.getInstance();
cal1.set(Calendar.HOUR, hourInt);
cal1.set(Calendar.MINUTE, minInt);
cal1.set(Calendar.SECOND, secInt);
long codeBase = cal1.getTime().getTime();
System.out.println("Code Base..."+codeBase);
chronometer.setBase(codeBase);
chronometer.start();
it display special chraracter like 00:0) and 00:0* and all special character.
how to set custom long value.

I was struggling with this myself until I managed to figure it out through trial and error.
Chronometer.setBase() wants millis based on the elapsed real time. This means that epoch milliseconds don't work. In order to be able to use epoch milliseconds, you have to call Chronometer.setBase() like this:
chronometer.setBase(SystemClock.elapsedRealtime() -
System.currentTimeMillis() + codeBase);
The math effectively converts the epoch milliseconds to elapsed real time milliseconds.

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 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/

Anyway of using before time function and equal to?

i am using the code below:
endTimeEntryCal2.before(addTimeEntryCale)
to check if user set time is before current time but i also want it to be before or equal to is there anyway of doing this here eg something like before=();
This does the trick:
endTimeEntryCal2.compareTo(addTimeEntryCale) <= 0
int compareTo(Calendar anotherCalendar)
Compares the times of the two Calendar, which represent the
milliseconds from the January 1, 1970 00:00:00.000 GMT (Gregorian).
Parameters anotherCalendar another calendar that this one is compared with
Returns:
0 if the times of the two Calendars are equal,
-1 if the time of this Calendar is before the other one
1 if the time of this Calendar is after the other one.
long mills = cal.getTimeInMillis();
long currentTime = System.currentTimeMillis();
int x = (mills <= currentTime)?0:1;
if(x == 1)
{
// Time Available
}else
{
//Time passed
}

Android: SimpleDateFormat keeps adding 1 hour to my time

I'm using currentTimeMillis(); to get a start time, then later using it again to get an end time. I then use delete start from end and get a value which is the duration between the two. I am using SimpleDateFormat to make all these values pretty and readable. the only thing is when i'm using a low value like 10 seconds (or 300 etc) and not the full blown long number (i.e. 1335718053126) I appear be getting out 01:00:10 or 01:02:12 etc on all my outputs? in fact if I just ask SimpleDateFormat to output a hh:mm:ss value against a 0 value it reads 01:00:00.
any one know why this is?
Found this neat little code if anyone else needs a solution to time formatting.
Source link
public String getNiceTime(long time) {
String format = String.format("%%0%dd", 2);
String seconds = String.format(format, time % 60);
String minutes = String.format(format, (time % 3600) / 60);
String hours = String.format(format, time / 3600);
String outPutTime = hours + ":" + minutes + ":" + seconds;
return outPutTime;
}
mySimpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
Explanation: you are probably living in a GMT+1 time zone and unless you specify a different one, your formatter will pick your current one, so it considers 0 hours as GMT and as you are in GMT+1, it outputs 1 hour

Add a certain amount of time to a current time and write it

I'm using:
Calendar c = Calendar.getInstance();
with which i get a current time,
String sHour = c.get(Calendar.HOUR_OF_DAY)
String sMinute = c.get(Calendar.MINUTE)
What i need is to add e.g. 1 Hour 10 Minutes - store it in a variable and also Substract let's say 10 minutes and save that as an another variable. (I need to use them both in a TextView)
I've seen the add(); method in Android documentation but I can't seem to understand how it works. Thanks
The code you've posted won't compile, as Calendar.get() doesn't return a string. You should also note that calendar is mutable - it's not like each call to add returns a new calendar. So you'll need to create a new instance each time you want a separate variable for a different value. For example:
Calendar now = Calendar.getInstance();
Calendar tmp = (Calendar) now.clone();
tmp.add(Calendar.HOUR_OF_DAY, 1);
tmp.add(Calendar.MINUTE, 10);
Calendar nowPlus70Minutes = tmp;
tmp = (Calendar) now.clone();
tmp.add(Calendar.MINUTE, -10);
Calendar nowMinus10Minutes = tmp;
If at all possible, I'd strongly recommend that you use Joda Time instead of Calendar/Date - it's a far superior API. You may want to trim the time zones included with it, however, so that it's faster to get started and less overhead in your apk.
You can simply call System.currentTimeMillis() + INTERVAL.
Where INTERVAL is the interval in milliseconds (for example:
public static final long INTERVAL = 1000 * 60 * 60 * 24; // 1 day

Categories

Resources