Determining if a time is between two other times - android

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.

Related

Changing Textview Dynamicly after a certain period of Days

I'm quite new to Android and I want to change (I know how to set it dynamically but....)Textview Dynamically after a certain period of Days,but int the meantime keep the text posted unless changed by user or if a certain days have been reached by my program.
Well Basically I have the user to input a Date then i want my program to count days and as long as the user nor my program have intervene with the textview it will show the same text and backround color until the opposite is taken action.
here is my code:
String CurrentDate = new SimpleDateFormat("dd/MM/yyyy").format(new Date());
String FinalDate = TvDateOfService.getText().toString();
SimpleDateFormat dates = new SimpleDateFormat("dd/MM/yyyy");
Date dateinput;
Date datetwra;
//Setting dates
try {
dateinput = dates.parse(FinalDate);
datetwra = dates.parse(CurrentDate);
//Comparing dates
long difference = Math.abs(dateinput.getTime() - datetwra.getTime());
long differenceDates = difference / (24 * 60 * 60 * 1000);
//Convert long to String
String dayDifference = Long.toString(differenceDates);
//Calendar Instance to Add 89 Days for Service Period Between Dates!!
Calendar cal1 = Calendar.getInstance();
cal1.add(Calendar.DATE, 90);
Date ServicePeriod = cal1.getTime();
Calendar cal2 = Calendar.getInstance();
cal2.add(Calendar.DATE, 80);
Date DaysBeforeEnd = cal2.getTime();
do {
tvStatus.setBackground(getApplicationContext().getResources().getDrawable(R.drawable.textview_backround_green));
}while (dateinput.before(DaysBeforeEnd));
do {
tvStatus.setText("something");
tvStatus.setBackground(getApplicationContext().getResources().getDrawable(R.drawable.textview_backround_yellow));
}while (dateinput.after(DaysBeforeEnd));
do {
tvStatus.setText("something else");
tvStatus.setBackground(getApplicationContext().getResources().getDrawable(R.drawable.textview_backround_red));
}while (dateinput.after(ServicePeriod));
It looks like you're trying to use a for loop and wait a certain number of days - it would be most beneficial to the phone's battery if you used AlarmManager
https://developer.android.com/trai.../scheduling/alarms.html

Time format bug for 12 AM/PM in android

Im creating an alarm apps for android. I dont really understand about time format so i go googling and got this post.
I followed that post, but a bug still remains : My apps cant tell the difference between (lets say) 12:17 AM and 12:17 PM. So the bug will occurred if the hour is 12.
What i did when taking the value form the TimePicker (hh:m:aa) format :
String hour = "";
Calendar datetime = Calendar.getInstance();
datetime.set(Calendar.HOUR_OF_DAY, timeSchedule.getCurrentHour());
datetime.set(Calendar.MINUTE, timeSchedule.getCurrentMinute());
if (datetime.get(Calendar.AM_PM) == Calendar.AM && timeSchedule.getCurrentHour() == 0) //12 AM = 0
hour = "00"+ ":" + timeSchedule.getCurrentMinute();
else
hour = timeSchedule.getCurrentHour() + ":" + timeSchedule.getCurrentMinute();
With above code, 12:17 AM will become 00:17 while 12:17PM will become 12:17PM. This value is stored in the mysql Time format. Since i want to create an alarm apps, please kindly tell me whether i did is right or not.
And this is what i did to show them to the user, where 00:17 (taken from the result of above code) become 12:17AM (correct) but 12:17 become 12:17AM (wrong) :
String time = getItem(position).getTime(); //value from above code
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss");
SimpleDateFormat newFormat = new SimpleDateFormat("hh:mm:aa");
String formatedTime = "";
try {
Date date = format.parse(time);
formatedTime = newFormat.format(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
To be honest, this is the first time i deal with somekind of alarm app, so please kindly tell me if i do something wrong. (beside my bug)
Thanks for your time.
UPDATE
This is what i did now :
I changed the mysql column from Time to Varchar, because Time wont let me insert "AM/PM".
After that :
String hour = "";
Calendar datetime = Calendar.getInstance();
datetime.set(Calendar.HOUR_OF_DAY, timeSchedule.getCurrentHour());
datetime.set(Calendar.MINUTE, timeSchedule.getCurrentMinute());
String am_pm = "";
if (datetime.get(Calendar.AM_PM) == Calendar.AM)
am_pm = "AM";
else
am_pm = "PM";
hour = (datetime.get(Calendar.HOUR) == 0) ?"12":datetime.get(Calendar.HOUR)+"";
final String time = hour+ ":" + datetime.get(Calendar.MINUTE) + " " + am_pm ;
Above code return 12:17 AM and 12:17 PM. With this, i dont have to use SimpleDateFormat to re-format the date again. Is this the correct way to set the time for alarm?
I am a bit confused with the notation you want to use. There are two approaches for representing AM, PM hours. Either in the range of 0:00-11:59 or in the range 1:00-12:59. You do not use either, thus you get troubles in representing the hours you encounter. PLease read through the different options provided in SimpleDateFormat.
Also restrain from using your own conversition - use the sdk class everywhere, thus you will ensure you do not get into made up format.

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/

How to fetch current GMT value?

In my app, I am using GeoNamesAPI for fetching the current time at any location.
I have registered for using that.
My code looks like:
Timezone currentTimeZone;
org.geonames.WebService.setUserName("mathew");
currentTimeZone = GeoNamesAPI.fetchTimeZone(latitude, longitude);
The problem is when I check time at any ocean, this currentTimeZone returns null.
So in that case, I show the GMT value.
String time = null;
Integer timeZone = (int) (((longitude / 7.5) + 1) / 2);
if (timeZone >= 0) {
time = "GMT+" + timeZone;
} else {
time = "GMT" + timeZone;
}
So the time value will be of the kind GMT+somevalue. I want to find another solution for this case. In this case also I want to display the time value. How can I do that? Is there any way to get the GMT value? Note: I dont want to show the date only time is required.
Thanks in advance.
I got it worked. Code is given below:
Integer timeZone = (int) (((longitude / 7.5) + 1) / 2);
DateFormat dateformat = DateFormat.getTimeInstance(DateFormat.SHORT);
dateformat.setTimeZone(TimeZone.getTimeZone("gmt"));
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR, timeZone); //Adding/Subtracting hour to current date time
String newdate = dateformat.format(cal.getTime());

The time my application displays does not change

I have a program which should display the current time. It displays the right time immediately after I install it to a phone. But after that, whenever I run the application, the time doesn't change at all.
Here's my code:
Calendar cal = new GregorianCalendar();
hour = cal.get(Calendar.HOUR);
minute = cal.get(Calendar.MINUTE);
second = cal.get(Calendar.SECOND);
year = cal.get(Calendar.YEAR);
month = cal.get(Calendar.MONTH)+1;
day = cal.get(Calendar.DATE);
date = day+"_"+month+"_"+year+"_";
Current_Time = date+ hour + "_" + minute + "_" + second;
Shekhar... I had the same misunderstanding. When you create an instance of calendar, it represents the date at which it was instantiated and that state does not change! So, to get the current "date" you need to create a new instance.
JAL
You can write it as a method. Each call to create a new instance of the Calendar

Categories

Resources