how to implement timer for quiz game in android - java

I am working on creating an android quiz game. I want to implement timer for each level to calculate how fast the user can answer all the questions. between each level there is an activity which i want to show the time taken to answer the quiz in the previous level before proceed into the next level. Can I get a guide on how to implement this? Thank you in advance

You can do something like this, when the user starts quiz and enters into your first level, then inside onCreate take start time like this:
Calendar calendar;
SimpleDateFormat df;
String template = "yyyy-MM-dd HH:mm:ss";
calendar = Calendar.getInstance();
df = new SimpleDateFormat(template, Locale.getDefault());
//this will give you the start time
String startTime = df.format(calendar.getTime());
//when user finishes up the level again record the finish time
String finishTime = df.format(calendar.getTime());
//then compare the two times
Date d1 = null;
Date d2 = null;
try {
d1 = df.parse(startTime);
d2 = df.parse(finishTime);
} catch (ParseException e) {
e.printStackTrace();
}
//in milliseconds
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000;
long diffMinutes = diff / (60 * 1000);
long diffHours = diff / (60 * 60 * 1000);
Hope it helps!!

Related

How to get number of hours between 2 System.currentTimeMillis()

I have saved the record insertion time in System.currentTimeMillis(). Now at present time, I know the current System.currentTimeMillis().
I want to know the difference between the 2 in terms of number of hours passed.
When i use this
System.currentTimeMillis()/(60 * 60 * 1000 ) - savedDate/(60 * 60 * 1000)
It gives me this number 414419 in output
Kindly guide me how to get number of hours from currentTimeMillis
Try to use android's time util class to solve your problem
private long hourDifference(long millisFirst, long millisSecond) {
return TimeUnit.MILLISECONDS.toHours(millisSecond - millisFirst);
}
You have to add bracket arround the multiplication:
System.currentTimeMillis()/(60 * 60 * 1000 ) - savedDate/(60 * 60 * 1000)
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");
Date resultdate = new Date(yourmilliseconds);
System.out.println(sdf.format(resultdate));
This may help you.
long diffInMillisec = System.currentTimeMillis() - savedDate;
long diffInSec = TimeUnit.MILLISECONDS.toSeconds(diffInMillisec);
seconds = diffInSec % 60;
diffInSec/= 60;
minutes =diffInSec % 60;
diffInSec /= 60;
hours = diffInSec % 24;

Android Java Refresh / Reload App Fragment

How is it possible in Android Java to refresh / reload the fragment page / pages.
I have 4 Fragment pages, with a date counter, which shows the month,weeks,days,minutes to a specific date.
The problem is that it does not update if the application is open.
lets say it says 1 day 2 weeks 10 minutes to a date, when I let the app open for 2 minutes the minute counter won't change.
Piece of code:
// date format
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
// current date time
String now = format.format(Calendar.getInstance().getTime());
// specific date
String date01 = "22/12/2015 21:10:00";
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(now);
d2 = format.parse(date01);
} catch (ParseException e) {
e.printStackTrace();
}
long diff = d2.getTime() - d1.getTime();
if (diffDays >= 0 && diffHours >= 0 && diffMinutes > 0) {
((TextView) android.findViewById(R.id.rest_time)).setText(diffDays + days
+ diffHours + hours + diffMinutes + minutes);
so calculation works.
Consider using d2.compareTo(d1) instead or simpler .after() and .before()

mean time of two string time in java

I have two times variable as string
want to find the mean time. please help me
inTime = shift.getInTime()+":00";
outTime = shift.getOutTime()+":00";
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
Date d1=df.parse(inTime);
Date d2 = df.parse(outTime);
long date1InMilSec=d1.getTime();
long date2InMilSec=d2.getTime();
long half =date1InMilSec + ((date2InMilSec - date1InMilSec) / 2);
long minute = (half / (1000 * 60)) % 60;
long hour = (half / (1000 * 60 * 60)) % 24;
String time = String.format("%02d:%02d", hour, minute);
First of all, if I use your code and set fixed time values, then I get 11:30:00 instead of your 07:00:00, so there is maybe something else wrong with inTime and outTime.
Since I get 11:30:00 there is maybe something wrong with your calculation of hour and minute, but I won't bother that. Let's use a new Date instance to do the conversion:
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
Date d1 = df.parse("09:30:00");
Date d2 = df.parse("15:30:00");
long date1InMilSec = d1.getTime();
long date2InMilSec = d2.getTime();
long half = date1InMilSec + ((date2InMilSec - date1InMilSec) / 2);
Date meanTime = new Date(half); // new Date instance, instead of own calculation
String time = df.format(meanTime);
System.out.println(time);
This code prints:
12:30:00
String inTime = "09:30:00";
String outTime = "15:30:00";
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
Date dateIn = df.parse(inTime);
Date dateOut = df.parse(outTime);
long dateInMill = dateIn.getTime();
long dateOutMill = dateOut.getTime();
long dateMiddleMill = dateInMill + ((dateOutMill - dateInMill) / 2);
Date dateMiddle = new Date(dateMiddleMill);
System.out.println(df.format(dateMiddle));

An hour of difference when substracting two long values

I am trying to generate the total time taken by my program to complete its job to print at the end of the program's execution. Following are the lines of code, I am using, to achieve this.
long startTime = System.currentTimeMillis(), endTime;
//actual programming logic
endTime = System.currentTimeMillis();
System.out.println((new SimpleDateFormat("HH:mm:ss.SSS").format(new Date(endTime).getTime() - new Date(startTime).getTime())));
The result here is 01:00:00.582 in place of 00:00:00.582. While I can imagine, this may be a very commonly faced issue, I tried my best to search with best keywords for this issue on web but nothing caught my eyes yet. Could someone throw some light on this?
Any responses are much aprpeciated. Thank you.
When running code similar to your code:
long startTime = System.currentTimeMillis(), endTime;
try { Thread.sleep(582); } catch (InterruptedException ignored) {}
endTime = System.currentTimeMillis();
System.out.println((new SimpleDateFormat("HH:mm:ss.SSS").format(
new Date(endTime).getTime() - new Date(startTime).getTime())));
I get this output:
16:00:00.582
Showing the date reveals the time zone I'm in (UTC-8):
System.out.println((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(
new Date(endTime).getTime() - new Date(startTime).getTime())));
Output:
1969-12-31 16:00:00.582
You are constructing a Date whose zero value is 00:00:00 January 1, 1970 UTC, but that is constructed in your own local time zone, which appears to have been one hour ahead of UTC on January 1, 1970.
Don't construct a Date using a time interval.
I managed to produce what I am looking for. Here is the code for it, if someone needs it:
static String fn_Z_getTimeDifference(Long startTime, Long endTime)
{
long processTime = endTime - startTime;
long days = processTime / 86400000L;
processTime -= days * 86400000L;
long hours = processTime / 3600000L;
processTime -= hours * 3600000L;
long mins = processTime / 60000L;
processTime -= mins * 60000L;
long seconds = processTime / 1000L;
processTime -= seconds * 1000L;
long milliSeconds = processTime ;
return (Long.toString(hours)+ ":" + Long.toString(mins) + ":" + Long.toString(seconds) + ":" + Long.toString(milliSeconds)).toString();
}
You are formatting a number, because of wrapping and undwrapping the longs.
Try this
).format(new Date(endTime - startTime)));
or at the very least
").format(new Date(new Date(endTime).getTime() - new Date(startTime).getTime()))));

How to check if the difference between 2 dates is more than 20 minutes

I have a datetime in a variable previous. Now i want to check if the previous datetime is more than twenty minutes before the current time.
Date previous = myobj.getPreviousDate();
Date now = new Date();
//check if previous was before 20 minutes from now ie now-previous >=20
How can we do it?
Use
if (now.getTime() - previous.getTime() >= 20*60*1000) {
...
}
Or, more verbose, but perhaps slightly easier to read:
import static java.util.concurrent.TimeUnit.*;
...
long MAX_DURATION = MILLISECONDS.convert(20, MINUTES);
long duration = now.getTime() - previous.getTime();
if (duration >= MAX_DURATION) {
...
}
Using Joda Time:
boolean result = Minutes.minutesBetween(new DateTime(previous), new DateTime())
.isGreaterThan(Minutes.minutes(20));
Java 8 solution:
private static boolean isAtleastTwentyMinutesAgo(Date date) {
Instant instant = Instant.ofEpochMilli(date.getTime());
Instant twentyMinutesAgo = Instant.now().minus(Duration.ofMinutes(20));
try {
return instant.isBefore(twentyMinutesAgo);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
You should really use Calendar object instead of Date:
Calendar previous = Calendar.getInstance();
previous.setTime(myobj.getPreviousDate());
Calendar now = Calendar.getInstance();
long diff = now.getTimeInMillis() - previous.getTimeInMillis();
if(diff >= 20 * 60 * 1000)
{
//at least 20 minutes difference
}
Get the times in milliseconds, and check the difference:
long diff = now.getTime() - previous.getTime();
if (diff > 20L * 60 * 1000) {
// ...
}
Another solution could be to use Joda time.

Categories