Calendar giving me the wrong hour and minute - android

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

Related

Get The Last Number of the Clock Time as Integer

What im asking here is Not very commons & im Not even sure if this is Possible,
I know How to get the Current Device Time by using this Code(return as a String) :
SimpleDateFormat Date = new SimpleDateFormat("hh:mm");
String DateTime = Date.format(new Date());
What im looking for is to Get the Last Number of the Minute as an Integer,
Eg. : The Time is 7:24 So i want to get the 4(Last Number) as an Integer,
It is Possible, if so, How ?
Alternatively you could work without using the SimpleDateFormat, but with the Calendar
int lastDigit = Calendar.getInstance().get(Calendar.MINUTE) % 10;
int lastDigit = Data.getDate().getMinutes % 10; // deprecated
I don't have much reputation to answer it in comments but i think what you have to do is get seconds in a variable and create sub-string and convert that string into integer.
I will Answer myself, the Solution was very simple :
SimpleDateFormat Date = new SimpleDateFormat("hh:mm");
String DateTime = Date.format(new Date());
int integer= Integer.parseInt(DateTime.substring(DateTime.length() - 1));
Toast.makeText(this, String.valueOf(integer), Toast.LENGTH_LONG).show();
Thanks
dateTime.substring(dateTime.length() - 1, dateTime.length())
*Side note - the convention for Java variable names is to start with a lower case letter. You have used upper case for the first letter in your variable names. Date.format may cause confusion to some people as it looks like a reference to a static method in the Date class.
Try this:
int lastMin = (int)((System.currentTimeMillis()/60000l) % 10);
Gives me 7 at 16:17 o'clock

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.

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 Run AsyncTask at a certain time from a Activity?

I have an AsyncTask in a activity that i only want to run once a week. How do i go about doing this?
I am retrieving a list of URL's about 7 of them and then putting them in SharedPreference.
i only want to update and check for new URL's once a week from my activity. This will be in my Main Activity.
You could save the date when you use the asynctask in the shared preferences.
So whenever the Main Activity starts you can check the current date and the date in the shared preferences, if its more than 7 days, you can do your asynctask again and update the saved date to the current date.
I believe you already know how to put strings inside shared preferences and to access them.
This is just the basic code of what to do. You will need to modify it a bit to get it working for you.
private static String getToday(){
Calendar objCalendar = new GregorianCalendar(Calendar.getInstance().getTimeZone());
DateFormat objFormatter = new SimpleDateFormat("dd-MM-yyyy");
return objFormatter.format(objCalendar.getTime());
}
private static String getAfter7DaysDate(){
Calendar objCalendar = new GregorianCalendar(Calendar.getInstance().getTimeZone());
DateFormat objFormatter = new SimpleDateFormat("dd-MM-yyyy");
objCalendar.add(Calendar.DATE, 7);
return objFormatter.format(objCalendar.getTime());
}
public int daysBetween(Date d1, Date d2){
return (int)( (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
}
If you put this in the onCreate
String today = getToday();
String afterSevenDate = getAfter7DaysDate();
DateFormat objFormatter = new SimpleDateFormat("dd-MM-yyyy");
try {
Log.e(today,Integer.toString(daysBetween(objFormatter.parse(today),
objFormatter.parse(afterSevenDate))));
} catch (ParseException e) {
e.printStackTrace();
}
The above code just retrieves the current date, the date after 7 days, and also find the difference in days between the 2 dates. You will need to get the saved date and find the after 7 days date and check if the differnce between the current date is >= to 7. If its true, do your async task.
This is the simple way to do it.
As JoeLallouz mentioned this will only work if user goes to that activity. But it will work even if he opens after a month due to the >= checking. But if you need to do it even if the user doesn't open you're app, you will need to look into the AlarmManager class.

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