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/
Related
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.
Essentially what I have is a string which contains a files Last Modified Date. To get this I'm using:
Date lastModDate = new Date(file.lastModified());
SimpleDateFormat formatter = new SimpleDateFormat("K:mm a");
String formattedDateString = formatter.format(lastModDate);
The end result is somewhat like 6:12 AM. What I want to do is each time a certain period of time is passed, the dateformat must change. E.g.
After 1 Day has gone by, Last Modified Date = ("Format1");
After a Week has gone by, Last Modified Date = ("Format2");
After 2 Weeks have gone by, Last Modified Date = ("Format3");
Does it make sense? If so is someone please be able to show me how it's done. A good example is the native Messaging App. When a message is created, It will show it's Time then after some days gone by the format changes to the Date it was created then the month etc...
I'm trying to do exactly that.
Calculate the difference in time between the last modified date and now:
long duration = lastModDate.getTimeInMillis() - current.getTimeInMillis();
long sec = TimeUnit.MILLISECONDS.toSeconds(duration);
boolean inFuture = sec > 0;
// Use positive value
if(!inFuture)
sec = -sec;
long minutes = sec / 60 % 60;
long hours = sec / 3600 % 24;
long days = sec / 86400;
if(days > 1 && days < 7)
// Use format 1
else if(days >= 7 && days < 14)
// Use format 2
else
// Use format 3
I am trying to get the time of a timestamp but I keep getting the wrong time when I use Calendar.HOUR and Calendar.MINUTE,no matter what the timestamp is it tells me the hour is 10 and the minute is 12.
now when I use the Calendar.getTime() it gives me the correct time so I dont understand? I just want to get the hour in 12hr format and the minute
here is how i go about doing it
public static String getRealTime(long time){
Calendar cal = Calendar.getInstance();
Log.d("Calendar",String.valueOf(time));
cal.setTimeInMillis(time);
Date timeS = cal.getTime();
String sTime = timeS.toString(); // gives correct time in 24hr format
int hr = cal.HOUR; // gives me 10 no matter what the timestamp is
int min = cal.MINUTE; // gives me 12 no matter what the timestamp is
String dMin = getDoubleDigit(min);
int ampm = cal.AM_PM;
String m = new String();
if(ampm == 0){
m = "AM";
}else{
m="PM";
}
String rtime = String.valueOf(hr)+":"+dMin+" "+m;
return rtime;
}
so say the timestamp is 1316626200000 cal.getTime() gives me Wed Sep 21 13:30:00 EDT 2011 which would be the correct time but cal.HOUR gives me 10 for the hour which clearly is not what it should be. Why is it doing that?
cal.HOUR and cal.MINUTE are static final Integers for use in Calendar method calls. You would use this code to get the correct result:
int hr = cal.get(Calendar.HOUR);
int min = cal.get(Calendar.MINUTE);
Notice that I called the HOUR and MINUTE fields from Calendar and not your object cal. It is bad practice to call static members from an instantiated object.
The great and almighty Android Reference page to the rescue!!! :D http://developer.android.com/reference/java/util/Calendar.html
So, here's the lowdown on why some of those things aren't returning the results you are expecting. First off, the Calendar.HOUR is not a reference to the current hour. First hint at that is the fact that it is in all caps, which by Java convention means that this is a constant (aka final) field. If you are developing in Eclipse it probably brought up a warning saying that you should probably reference the static variable with the class name Calendar instead of using the instance cal. Second hint: the reference page said so! ;)
Well, what should you do with the Calendar.HOUR then? That is a static constant so that you can use the cal.get() to find out. (see the reference page http://developer.android.com/reference/java/util/Calendar.html#get(int))
But! There is an easier way. The code that you might be looking for could be something like this:
public static String getRealTime(long time){
return new SimpleDateFormat("HH:mm").format(new Date(time));
//if you'd rather have the current time, just use new Date() without the time as a parameter
}
Another user has asked for a sorta similar things and there are a few other implementations on this page Display the current time and date in an Android application
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.
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