I am building a quiz and i need to calculate the total time taken to do the quiz.
and i need to display the time taken in HH::MM::SS..any pointers?
new Date().time returns the time in milliseconds.
var nStart:Number = new Date().time;
// Some time passes
var nMillisElapsed:Number = new Date().time - nStart;
var strTime:String = Math.floor(nMillisElapsed / (1000 * 60 * 60)) + "::" +
(Math.floor(nMillisElapsed / (1000 * 60)) % 60) + "::" +
(Math.floor(nMillisElapsed / (1000)) % 60);
I resurrect this question to say that both Brian and mica are wrong. Creating a new Date() gives you the time according to the computer's clock. All someone has to do is set their clock back several minutes, and that would cause the quiz timer to go back several minutes as well. Or worse, they could set their clock back to a time before they started the quiz, and your app would think they spent a negative amount of time taking the quiz. o.O
The solution is to use flash.utils.getTimer(). It returns the number of milliseconds since the swf started playing, regardless of what the computer's clock says.
Here's an example:
var startTime:Number = getTimer();
// then after some time passes:
var elapsedMilliseconds:Number = getTimer() - startTime;
Then you can use Brian's code to format the time for display:
var strTime:String = Math.floor(elapsedMilliseconds / (1000 * 60 * 60)) + "::" +
(Math.floor(elapsedMilliseconds / (1000 * 60)) % 60) + "::" +
(Math.floor(elapsedMilliseconds / (1000)) % 60);
Fill with zero when number is less than 10 (Thanks brian)
var now:Date; //
var startDate:Date;
var startTime:Number;
// initialize timer and start it
function initTimer():void{
startDate = new Date();
startTime = startDate.getTime();
//
var timer:Timer = new Timer(1000,0); // set a new break
timer.addEventListener(TimerEvent.TIMER, onTimer); // add timer listener
//
function onTimer():void{
now=new Date();
var nowTime:Number = now.getTime();
var diff:Number = nowTime-startTime;
var strTime:String = Math.floor(diff / (1000 * 60 * 60)) + ":" +
zeroFill(Math.floor(diff / (1000 * 60)) % 60) + ":" +
zeroFill(Math.floor(diff / (1000)) % 60);
// display where you want
trace('time elapsed : ' + strTime);
}
// fill with zero when number is less than 10
function zeroFill(myNumber:Number):String{
var zeroFilledNumber:String=myNumber.toString();
if(myNumber<10){
zeroFilledNumber = '0'+zeroFilledNumber;
}
return zeroFilledNumber;
}
// start TIMER
timer.start();
}
initTimer();
var countdown:Timer = new Timer(1000);
countdown.addEventListener(TimerEvent.TIMER, timerHandler);
countdown.start();
function timerHandler(e:TimerEvent):void
{
var minute = Math.floor(countdown.currentCount / 60);
if(minute < 10)
minute = '0'+minute;
var second = countdown.currentCount % 60;
if(second < 10)
second = '0'+second;
var timeElapsed = minute +':'+second;
trace(timeElapsed);
}
Related
I need assistance. I got some of this code off another site. It was randomly generating a date for the previous 7 days and randomly generating an hour and minute within a 24 hour period (any). I need the opposite of sorts. I need a random time that covers the current "now" time and goes forward 7 days but also requires the time (hour and minute) to be within a set hour range.
Requirements
Random Date covering current day ("now") and ahead one week (7 days).
Random Time generated; however time must fall between the hours of 1000hrs to 2200hrs and formatted as ("yyyy-MM-dd'T'HH:mm:ss").
My BS PreProcessor Parameters I was passing for the below code are (1 5 5). My dates seem to generate just fine but my time is only generating random hours as hours within the next 5 hours. How can I set a time range of 10am-10pm?
import java.text.SimpleDateFormat;
import java.text.NumberFormat;
import java.util.Date;
import java.util.Random;
int minDay = Integer.parseInt(bsh.args[0]); // get first parameter minimal X Days ahead
int maxDay = Integer.parseInt(bsh.args[1]); // get second parameter maximal X Days ahead
int maxMinutesActivity = Integer.parseInt(bsh.args[2]); // get maximal duration of activity
int myThreadNum = 0;
int randomDay = 0; // RandomDays ahead
int minHour = 0;
int maxHour = 5;
int randomHour = 0;
int minMinute = 0;
int maxMinute = 60;
int randomMinute = 0;
int randomMinuteDuration = 0;
String formattedDate = "";
Random randomvar = new Random();
Date datevar = new Date();
Date datevarThisWeek = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
NumberFormat myFormat = NumberFormat.getInstance();
myFormat.setMinimumIntegerDigits(2); // required to have minimal two digits for Day, Hour, Minute
myThreadNum = ${__threadNum}; // just to show the thread number in debug
vars.put("myThreadNum",myFormat.format(myThreadNum));
randomDay = minDay+randomvar.nextInt(maxDay-minDay+1); // randomDays ahead between minDay and maxDay
datevar.setDate(datevar.getDate() - randomDay );
vars.put("randomDay",myFormat.format(randomDay));
randomHour = 1+randomvar.nextInt(maxHour-minHour+1); // randomHour ahead between minHour and maxHour
vars.put("randomHour",myFormat.format(randomHour));
randomMinute = minMinute+randomvar.nextInt(maxMinute-minMinute+1); // randomHour ahead between minMinute and maxMinute
vars.put("randomMinute",myFormat.format(randomMinute));
randomMinuteDuration = maxMinutesActivity; // randomduration between 1 and maxMinutesActivity
vars.put("randomMinuteDuration",myFormat.format(randomMinuteDuration));
// Calculate a Start and End time for this Week
randomDay = 1+randomvar.nextInt(5-1+1); // randomDays ahead this Week
datevarThisWeek.setDate(datevarThisWeek.getDate() + randomDay );
datevarThisWeek.setTime(datevarThisWeek.getTime() + ((randomMinute + (randomHour * 60 )) * 60 * 1000 ));
//datevarThisWeek.setTime(datevarThisWeek.getTime() + ((randomMinute + (randomHour * 60 )) * 60 * 1000 ) + myThreadNum );
formattedDate = df.format(datevarThisWeek);
vars.put("randomFireTime_FUTURE",formattedDate);
datevarThisWeek.setTime(datevarThisWeek.getTime() + (randomMinuteDuration * 60 * 1000 ));
//datevarThisWeek.setTime(datevarThisWeek.getTime() + (randomMinuteDuration * 60 * 1000 ) + myThreadNum );
formattedDate = df.format(datevarThisWeek);
vars.put("randomOrderTime_FUTURE",formattedDate);
Java fake library Might helps you.
import com.github.javafaker.Faker;
Date dob= faker.date().between(date1,date2);
Hi guys, I'm trying to look for a way on how to make the Time Left column count down. I was guessing on doing it via ajax and updating it every minute but I guess it will affect the performance. What is the best way to achieve this? I need it to show the real-time time left of the column also updating the values in the database. Thank you!
You do not to update the time left everytime in the database, I don't think you need to even store it. You need to store the deadline (The End Date) and then the count down will be only on the client side using JavaScript as follows:
let timer = function (date) {
let timer = Math.round(new Date(date).getTime()/1000) - Math.round(new Date().getTime()/1000);
let minutes, seconds;
setInterval(function () {
if (--timer < 0) {
timer = 0;
}
days = parseInt(timer / 60 / 60 / 24, 10);
hours = parseInt((timer / 60 / 60) % 24, 10);
minutes = parseInt((timer / 60) % 60, 10);
seconds = parseInt(timer % 60, 10);
days = days < 10 ? "0" + days : days;
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
document.getElementById('cd-days').innerHTML = days;
document.getElementById('cd-hours').innerHTML = hours;
document.getElementById('cd-minutes').innerHTML = minutes;
document.getElementById('cd-seconds').innerHTML = seconds;
}, 1000);
}
//using the function
const today = new Date()
const tomorrow = new Date(today)
tomorrow.setDate(tomorrow.getDate() + 1)
timer(tomorrow);
<span id="cd-days">00</span> Days
<span id="cd-hours">00</span> Hours
<span id="cd-minutes">00</span> Minutes
<span id="cd-seconds">00</span> Seconds
I am new to programming, and on our programming class, we were asked to do an algorithm that counts the day before Christmas given a date. I have already an algorithm in mind, but it needs defining the number of days there are before Christmas for each month, then a lot of if-else statements. I was just wondering if there is another more efficient algorithm to this problem. I am writing this in pseudocode.
This is what I have done so far:
define jan=359, feb=328, mar=306, apr=269, may=239, jun=208, jul=178, aug=147, sep=116, oct=86, nov=55, dec=25
input mm
input dd
if mm is jan
days= jan - dd
...
This is a countdown function,
let dayMilli = (24*60*60*1000);
let hourMilli = (60*60*1000);
let minuteMilli = (60*1000);
let secondMilli = (1000);
function printTime(millis){
var days = millis/dayMilli;
var lessDay = millis % dayMilli;
var hours = lessDay/hourMilli;
var lessHour = lessDay % hourMilli;
var minute = lessHour/minuteMilli;
var lessMinute = lessHour % minuteMilli;
var second = lessMinute / secondMilli;
$("#myTime").text(parseInt(days) + " Days " + parseInt(hours) + " Hours " + parseInt(minute) + " Minutes " + parseInt(second) + " Seconds");
}
and if you need a countdown for every second you can try
//call every seconds the function update
var myVar = setInterval(update, 1000);
//date of christmas
var christmas = new Date(2018, 12, 25, 0, 0, 0, 0)
//update time difference
function update(){
printTime(getTimeDif(christmas));
}
//get milliseconds difference from today to christmas
function getTimeDif(dateBefore){
return (dateBefore.getTime()- new Date()).getTime());
}
I want to generate random number for refresh page
How to set math.random between 20 sec until 50 sec?
My Javascript code looks like this:
var number = Math.random() * 50;
var sec = number - (number % 1) + 20;
var url = "http://example.org";
if (sec == 20 || sec == 30 || sec == 40 || sec == 50)
{
setTimeout(function() { window.location = url } , sec * 1000 );
}
Based on this a suggest following statement:
var sec = Math.floor(Math.random() * (50 - 20) + 20);
I tested it with following script:
<script>
a = 20;
b = 50;
for (i = 0; i < 20; i++)
{
alert(Math.floor(Math.random() * (b - a) + a));
}
</script>
and it has never generated a number lower than 20 and higher than 50.
I have an hour selection drop down 0-23 and minutes selection drop down 0-59 for Start time and End time respectively (so four controls).
I'm looking for an algorithm to calculate time difference using these four values.
Since they're not stored in fancy date/time selection controls, I don't think I can use any standard date/time manipulation functions.
How do I calculate the difference between the two times?
This pseudo-code gives you the algorithm to work out the difference in minutes. It assumes that, if the start time is after the end time, the start time was actually on the previous day.
const MINS_PER_HR = 60, MINS_PER_DAY = 1440
startx = starthour * MINS_PER_HR + startminute
endx = endhour * MINS_PER_HR + endminute
duration = endx - startx
if duration < 0:
duration = duration + MINS_PER_DAY
The startx and endx values are the number of minutes since midnight.
This is basically doing:
Get number of minutes from start of day for start time.
Get number of minutes from start of day for end time.
Subtract the former from the latter.
If result is negative, add number of minutes in a day.
Don't be so sure though that you can't use date/time manipulation functions. You may find that you could easily construct a date/time and calculate differences with something like:
DateTime startx = new DateTime (1, 1, 2010, starthour, startminute, 0);
DateTime endx = new DateTime (1, 1, 2010, endhour , endminute , 0);
Integer duration = DateTime.DiffSecs(endx, startx) / 60;
if (duration < 0)
duration = duration + 1440;
although it's probably not needed for your simple scenario. I'd stick with the pseudo-code I gave above unless you find yourself doing some trickier date/time manipulation.
If you then want to turn the duration (in minutes) into hours and minutes:
durHours = int(duration / 60)
durMinutes = duration % 60 // could also use duration - (durHours * 60)
This will compute duration in minutes including the year as factor
//* Assumptions:
Date is in Julian Format
startx = starthour * 60 + startminute
endx = endhour * 60 + endminute
duration = endx - startx
if duration <= 0:
duration = duration + 1440
end-if
if currday > prevday
duration = duration + ((currday-preday) - 1 * 1440)
end-if
First you need to check to see if the end time is greater than or equal to the start time to prevent any problems. To do this you first check to see if the End_Time_Hour is greater than Start_Time_Hour. If they're equal you would instead check to see if End_Time_Min is greater than or equal to Start_Time_Min.
Next you would subtract Start_Time_Hour from End_Time_Hour. Then you would subtract Start_Time_Min from End_Time_Min. If the difference of the minutes is less than 0 you would decrement the hour difference by one and add the minute difference to 60 (or 59, test that). Concat these two together and you should be all set.
$start_time_hr = 5;
$start_time_mi = 50;
$end_time_hr = 8;
$end_time_mi = 30;
$diff = (($end_time_hr*60)+$end_time_mi) - (($start_time_hr*60)+$start_time_mi);
$diff_hr = (int)($diff / 60);
$diff_mi = (int)($diff) - ($diff_hr*60);
echo $diff_hr . ':' . $diff_mi;
simple equation should help:
mindiff = 60 + endtime.min - starttime.min
hrdiff = ((mindiff/60) - 1) + endtime.hr - starttime.hr
This gives you the duration in hours and minutes
h1 = "hora1"
m1 "min1"
h2 "hora2"
m2 = "min2"
if ( m1 > m2)
{
h3 = (h2 - h1) - 1;
}
else
{
h3 = h2 - h1;
}
m1 = 60 - m1;
if (m1 + m2 >= 60)
{
m3 = 60 - (m1 + m2);
} else if (m3 < 0)
{
m3 = m3 * -1;
}
else
{
m3 = m1 + m2;
}
System.out.println("duration:" + h3 + "h" + m3 + "min");
If you have a function that returns the number of days since some start date (e.g. dayssince1900) you can just convert both dates to seconds since that start date, do the ABS(d1-d2) then convert the seconds back to whatever format you want e.g. HHHH:MM:SS
Simple e.g.
SecondsSince1900(d)
{
return dayssince1900(d)*86400
+hours(d)*3600
+minutes(d)*60
+seconds(d);
}
diff = ABS(SecondsSince1900(d1)-SecondsSince1900(d2))
return format(diff DIV 3600)+':'+format((diff DIV 60) MOD 60)+':'+format(diff MOD 60);
Hum: Not that simple if you have to take into account the leap seconds astronomers are keen to put in from time to time.