Formatting time in Android Application - java

I've created an Android grading app to use within my classes. All the database connections and grading logic has been laid out and functions precisely as it should.
However, I am having a problem incorporating the Java Calendar class. I need to be able to limit each class to submit their answers "only" during their class time. As you can see, I will need to incorporate a series of "if statements" in order to do this.
The problem is that I don't know how to get this time that I need to verify that my student's answer submissions are only handled during their class time.
This is what I've tried:
Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR);
int minute = cal.get(Calendar.MINUTE);
As you can see, I am only able to get hours and minutes separate from each other. How do I get the real time? Just Hours and minutes not seconds.
In my code my set up should look like this:
int period = will be selected from a spinner object
if(period == 1 && (time>= 7:20 AM && time<= 9:00AM)) Then, go ahead and
submit your answers to online database.
if(period == 8 && (time>= 12:50PM && time<= 2:20PM)) Then, go ahead and
submit your answers to online database.
I don't know how to format this "time" object with the Calendar class.
Any help would be appreciated.

You can set hours and minutes to the calendar:
Calendar start = Calendar.getInstance();
start.set(Calendar.HOUR, 7);
start.set(Calendar.MINUTE, 20);
The same for the endDate:
Calendar end = Calendar.getInstance();
end.set(Calendar.HOUR, 9);
end.set(Calendar.MINUTE, 0);
To check that the current datetime is in the interval:
Calendar cal = Calendar.getInstance();//now
boolean isInInterval = cal.getTime().after(start.getTime()) && cal.getTime().before(end.getTime());

Related

How to compute times for alarm clock app?

I have a list of alarms specified by the user like a typical alarm clock app as:
day-of-week
hour-of-day
minute-of-hour
I'm hand-writing a function to go through a list of times specified this way and determine which is the next up-coming alarm compared to current time. I'll use AlarmManager ultimately to scheduling the next upcoming alarm once I determine which alarm is next. I have considered Date, Time, and GregorianCalendar classes because they have before() and after() methods but they are all a pain to construct given my parameters. Is there a better way than writing all the date/time subtraction math myself?
You could use the Calendar class for aiding the construction of dates. Then with the getDate method you could get milliseconds and deal with them for finding the closest alarm. Check an example of usage of Calendar here http://www.tutorialspoint.com/java/util/calendar_add.htm
You can use date object.Here is video lesson I found in youtube.
create digital clock
while(time == 0){
Calendar calen = new GregorianCalendar();
int hr = calen.get(Calendar.HOUR);
int min = calen.get(Calendar.MINUTE);
int sec = calen.get(Calendar.SECOND);
int AP = calen.get(Calendar.AM_PM);
String d_n = "";
if(AP == 1){
d_n = "PM";
}else{
d_n = "AM";
}
}

How to check if Current Hour falls between certain range

I am trying to check if Current Hour falls in between 7AM and 10AM
I am doing it this way
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
int hour = cal.get(Calendar.HOUR_OF_DAY);
if(hour >= 7 && hour <= 10)
{
}
Please tell me if this is a valid approach to follow
Yes that is a valid approach. You could also use the new Time API (needs Java 8)
import java.time.LocalTime;
...
int hour = LocalTime.now().getHour();
It's a bit shorter to get the hour. There is also an overloaded now(ZoneId zoneId) method.
Or make it a one liner with a temporal query (also needs Java 8):
Boolean isBetween7and10AM = LocalTime.now().query(date -> date.get(ChronoField.CLOCK_HOUR_OF_DAY) >=7 &&
date.get(ChronoField.CLOCK_HOUR_OF_DAY) < 10);
Yup. This looks fine. Remember that this Calendar field is dependent on the timezone.
BTW: Put the starting curly brace at the end of the previous line, since this is the common code formatting style.
:-)

Getting range of months - Java

I want to implement a tab layout with a range of months. This range should contain the last and next 12 Months.
I know how to get the next 12 months but i stuck at how to get the last AND next 12 months. I could use the joda time library but i think this lib is too big for my small android application.
Can anybody help my by providing a small code snipped? Thanks!
You can simply use a Calendar class instance to do it, with Calendar#add(int field,
int amount) like:
//getting month names
DateFormatSymbols dfs = new DateFormatSymbols();
String[] months = dfs.getMonths();
//here is what you need
Calendar c = Calendar.getInstance();
System.out.println(c.getTime().toString());
c.add(Calendar.MONTH, -12);
for (int i = -12; i <=12; i++){
c.add(Calendar.MONTH, +1);
System.out.println(months[c.get(Calendar.MONTH)]);
}
DateFormatSymbols is here used, to get the names of the months only.
You can use the calendar class to get the current month. Then u can subtract 1 to get the value of last month or add 1 to get next month.
Here is an example snippet.
Calendar calendar = Calendar.getInstance();
int month = calendar.get(Calendar.MONTH);
calendar.set(Calendar.MONTH, month - 1);
int lastMonth = calendar.get(Calendar.MONTH);
U could write a loop to calculate last and next 12 months this way.
Cheers :)

How to find out start of next day using Java

In my simple application, I am storing the timestamp into the database table programmatically by using new Timestamp(System.currentTimeMillis()).
Now, I have one condition, where I have to store the onClick count for a particular day, and all onClick counts into two different columns.
So for that, I need to find out onClicks for today. So how can I find out if the time onclicks occur are today? I mean for say 1st August, I want all the onclick counts in one column and all previous onClick counts into another column.
*In simple words - storing clicks for today in one column and storing clicks till now in another column, so if today expires, I want to add clicks for today with total clicks and then make the today_clicks column count to 0 and then when there is new click on next day, store it in the today_clicks column by starting it with count 1*
How can I decide that? Which Java class should I use for that?
Not sure if that is what are you after. To get start of next day you can use Calendar:
public static Date nextDayStart(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.add(Calendar.DATE, 1);
return cal.getTime();
}
To get tomorrow:
Date tomorrow = nextDayStart(new Date());
To get Timestamp from Date:
Timestamp s = new Timestamp(date.getTime());
If I understand correctly, you are looking for a way to best store your data in your database. You have decided to maintain a clicks-for-today column and a clicks-until-now column. (I may be off base on this, but it wasnt completely clear from the question)
I would suggest that you dont try to manipulate the data from column to column as you have described, but instead do so by maintaining click counts per day:
date | count
------|-------
Jul 31| 10876
Aug 1| 15721
(where date is a in the db timestamp/date datatype)
How would this work?
At startup, you could then bring into memory all rows, and sum their counts to get a clicks-until-now value, if needed.
You then have special handling for today's row, where you update the appropriate context with the clicks-for-today value.
To determine whether you've passed a day threshold, you could simply:
maintain a Calendar instance for 'today' (call it todayCal)
generate a new Calendar each time you record a click (call it clickCal)
test Calendar.DAY_OF_YEAR from todayCal and clickCal
if you identify a day roll, you persist the clicks-for-today in the db and initialized a new clicks-for-today.
if you are maintaining total click count in memory, you can do the math at this point.
First, I'd suggest taking a look at Joda Time.
Second, I'd take a look at Calendar:
Calendar lower = Calendar.getInstance();
lower.setTime(new Date());
lower.set(Calendar.HOUR_OF_DAY, 0);
lower.set(Calendar.MINUTE, 0);
lower.set(Calendar.SECOND, 0);
lower.set(Calendar.MILLISECOND, 0);
Calendar upper = Calendar.getInstance();
upper.setTime(new Date());
upper.set(Calendar.HOUR_OF_DAY, 23);
upper.set(Calendar.MINUTE, 59);
upper.set(Calendar.SECOND, 59);
upper.set(Calendar.MILLISECOND, 99);
Date clickTime = new Date(timeInMillis);
if (clickTime.after(lower.getTime()) && clickTime.before(upper.getTime())) {
// Is today
}

Android: compare calendar dates

In my app I´m saving when I last updated some data from my server.
Therefore I used:
long time = Calendar.getInstance().getTimeInMillis();
Now I want that the data is updated twice a year at 03.03 and 08.08.
How can I check wheater one of these two date boarders were crossed since last update?
Change them to time in mseconds and compare:
Calendar c = Calendar.getInstance();
c.set(Calendar.MONTH, Calendar.MARCH);
c.set(Calendar.DAY_OF_MONTH, 3);
long time2= c.getTimeInMillis();
c.set(Calendar.MONTH, Calendar.AUGUST);
c.set(Calendar.DAY_OF_MONTH, 8);
long time3= c.getTimeInMillis();
if(time>time2){
//Logic
if(time>time3){
//Logic
}
}
There is something very important which took me a while to figure it out and can be very helpful to people out there, if you are looking for an answer to any of the following questions this is for you:
Why is my date not showing correctly?
Why even when I set the time manually it is not showing right?
Why is the month and the year showing one day less than the one that I set?
For some reason Java sorts the months values like an array, what I mean is that for Java January is 0 and DECEMBER is 11. Same happens for the year, if you set December as month 12 and year as 2012, and then try to do a "system.out.println" of the month and the year, it will show my month as January and the year as 2013!!
so what should you do?
Calendar cal = new GregorianCalendar();
cal.set(2012, 11, 26); // the date I want to input is 26/12/2012 (for Java, 11 is December!)
NOW WHAT IS THE CORRECT WAY TO GET THAT DATE TO SEE IT ON THE SCREEN?
if you try to "system.out.println of yourCalendar.DATE, yourCalendar.MONTH and yourCalendar.YEAR," THAT WILL NOT SHOW YOU THE RIGHT DATE!!!!
If you want to display the dates you need to do the following:
System.out.println (calact.get (calact.DATE));
// displays day
System.out.println (calact.get (calact.MONTH)+1);
//add 1 remember it saves values from 0-11
System.out.println (calact.get (calact.YEAR));
// displays year
NOW IF YOU ARE HANDLING STRINGS THAT REPRESENT DATES, OR....
IF YOU NEED TO COMPARE DATES BETWEEN RANGES , LET'S SAY YOU NEED TO KNOW IF DATE "A" WILL TAKE PLACE WITHIN THE NEXT 10 DAYS....THIS....IS.....FOR....YOU!!
In my case I was working with a string that had format "15/07/2012", I needed to know if that date would take place within the next 10 days, therefore I had to do the following:
1 get that string date and transform it into a calendar ( StringTokenizer was used here )
this is very simple
StringTokenizer tokens=new StringTokenizer(myDateAsString, "/");
do nextToken and before returning the day, parse it as integer and return it.
Remember for month before returning substract 1.
I will post the code for the first you create the other two:
public int getMeD(String fecha){
int miDia = 0;
String tmd = "0";
StringTokenizer tokens=new StringTokenizer(fecha, "/");
tmd = tokens.nextToken();
miDia = Integer.parseInt(tmd);
return miDia;
}
2 THEN YOU CREATE THE CALENDAR
Calendar cal = new GregorianCalendar(); // calendar
String myDateAsString= "15/07/2012"; // my Date As String
int MYcald = getMeD(myDateAsString); // returns integer
int MYcalm = getMeM(myDateAsString); // returns integer
int MYcaly = getMeY(myDateAsString); // returns integer
cal.set(MYcaly, MYcalm, MYcald);
3 get my current date (TODAY)
Calendar curr = new GregorianCalendar(); // current cal
calact.setTimeInMillis(System.currentTimeMillis());
4 create temporal calendar to go into the future 10 days
Calendar caltemp = new GregorianCalendar(); // temp cal
caltemp.setTimeInMillis(System.currentTimeMillis());
caltemp.add(calact.DAY_OF_MONTH, 10); // we move into the future
5 compare among all 3 calendars
here basically you ask if the date that I was given is for sure taking place in the future AND (&&) IF the given date is also less than the future date which had 10 days more, then please show me "EVENT WILL TAKE PLACE FOR SURE WITHIN THE NEXT 10 DAYS!!" OTHERWISE SHOW ME:
"EVENT WILL NOT TAKE PLACE WITHIN THE NEXT 10 DAYS".
if((cal.getTimeInMillis() > curr.getTimeInMillis()) && (cal.getTimeInMillis()< curr.getTimeInMillis()))
{ System.out.println ("EVENT WILL TAKE PLACE FOR SURE WITHIN THE NEXT 10 DAYS!!");}
else
{ System.out.println ("EVENT WILL *NOT* TAKE PLACE WITHIN THE NEXT 10 DAYS");}
ALRIGHT GUYS AND GIRLS I HOPE THAT HELPS. A BIG HUG FOR YOU ALL AND GOOD LUCK WITH YOUR PROJECTS!
PEACE.
YOAV.
If the comparison should involve only the year, month and day then you can use this method for check if c1 is before c2. Ugly, but works.
public static boolean before(Calendar c1, Calendar c2){
int c1Year = c1.get(Calendar.YEAR);
int c1Month = c1.get(Calendar.MONTH);
int c1Day = c1.get(Calendar.DAY_OF_MONTH);
int c2Year = c2.get(Calendar.YEAR);
int c2Month = c2.get(Calendar.MONTH);
int c2Day = c2.get(Calendar.DAY_OF_MONTH);
if(c1Year<c2Year){
return true;
}else if (c1Year>c2Year){
return false;
}else{
if(c1Month>c2Month){
return false;
}else if(c1Month<c2Month){
return true;
}else{
return c1Day<c2Day;
}
}
}
used compareTo method ..and this returns integer value .if returns -ve the days before in current date else return +ve the days after come current date

Categories