How to do Countdown algorithm - algorithm

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());
}

Related

Laravel 7: How to add numeric value with date?

I'm calculating the difference between two dates. I want to make addition/subtraction a numeric/decimal value with the date.
Example:
Start = 2022-06-28
end = 2022-06-29
total= (start - 0.5) - ( end - 0)
= 1.5
or
total= (start - 0) - ( end - 0)
= 2
or
total= (start - 0.5) - ( end - 0.5)
= 1
Code:
$second_half = $request->session_1; // value = 0.5
$first_half = $request->session_2; // value = 0.5
$start = Carbon::parse($request->start_date); // value (YYYY-MM-DD) = 2022-06-28
$end = Carbon::parse($request->end_date); // value (YYYY-MM-DD) = 2022-06-29
$total_days = $end->diff($start); // this result can be decimal like 1.5
Actually, I want to divide the full day into two-part. First half and second half. So when I calculating the difference between two dates it should calculate the full day by (first half + second half). If I select 2022-06-28 first half and 2022-06-29 second half, it will count 2 days. If I select 2022-06-28 first half and 2022-06-29 first half, it will count 1.5 days.
I hope my concept is clear to you. How can I make this calculation?
Can you test please the followind code?
$startDate = '2022-06-28';
$endDate = '2022-06-29';
$second_half = 0.5;
$first_half = 0.5;
$start = \Carbon\Carbon::parse($startDate);
$end = \Carbon\Carbon::parse($endDate);
$total_days = (float) $end->diff($start)->days;
if($first_half) {
$total_days += $first_half;
}
if ($second_half) {
$total_days += $second_half;
}
$total_days = preg_replace('/\\.$/','.0',rtrim($total_days,'0'));
// dd($total_days);
$second_half = $request->session_1; // value = 0.5
$first_half = $request->session_2; // value = 0.5
$start = Carbon::parse($request->start_date . ($first_half ? ' 12:00' : ' 00:00'));
$end = $second_half
? Carbon::parse($request->end_date . ' 12:00')
: Carbon::parse($request->end_date)->addDay();
$total_days = $end->floatDiffInDays($start);

BeanShell PreProcessor (JMeter) - How can I generate a random future DateTime Stamp that covers current time out to 7 days?

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);

Countdown inside laravel blade

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

Count day combinations in the date range

Imagine that you have a range of dates, for example 2017-08-01 - 2017-09-15, and start day (Monday - sonday in numerical format 1-7) and endDay. You have to calculate the number of combinations of this days.
For the input 4-7 what is thusday - sonday and mentioned dates the output will be 6. How would you do that?
In your example you would have these values:
rangeStart = 2017-08-01
rangeEnd = 2017-09-15
startDay = 4
endDay = 7
I suppose you also have the following functions:
weekday(date) determines the day of the week for the given date, and returns it as a number: 1 for Monday, ... 7 for Sunday.
date_add(date, days) adds days days to the given date and returns the resulting date.
date_diff(date1, date2) returns the number of days between two dates, excluding date2 itself, i.e. when both dates fall on the same week day, this will be a multiple of 7.
Then this could be the algorithm:
# Align range start with closest start day in the range
rangeStart = date_add(rangeStart, (startDay + 7 - weekday(rangeStart)) % 7)
# Align range end with closest end day within the range
rangeEnd = date_add(rangeEnd, -((weekday(rangeEnd) + 7 - endDay) % 7))
# Get number of full weeks in range, and add 1
result = floor(date_diff(rangeStart, rangeEnd) / 7) + 1
NB: % is the modulo operator, and floor truncates a decimal number down to the nearest integer value.
Implementation in JavaScript:
// Define utility functions whose implementations depend on the programming language
function weekday(date) {
return (date.getDay()+6)%7+1; // in JavaScript Sunday is 0
}
function date_add(date, days) {
var result = new Date(date); // get clone
result.setDate(result.getDate() + days); // mutate
return result;
}
function date_diff(date1, date2) {
return Math.round((date2-date1)/(1000*60*60*24));
}
var floor = Math.floor;
// Main algorithm
function count(rangeStart, rangeEnd, startDay, endDay) {
rangeStart = date_add(rangeStart, (startDay + 7 - weekday(rangeStart)) % 7);
rangeEnd = date_add(rangeEnd, -((weekday(rangeEnd) + 7 - endDay) % 7));
return floor(date_diff(rangeStart, rangeEnd) / 7) + 1;
}
var rangeStart = new Date("2017-08-01"),
rangeEnd = new Date("2017-09-15"),
startDay = 4,
endDay = 7;
var result = count(rangeStart, rangeEnd, startDay, endDay);
console.log(result);
Implementation in Python:
import datetime
def count(rangeStart, rangeEnd, startDay, endDay):
rangeStart = rangeStart + datetime.timedelta((startDay + 7 - rangeStart.isoweekday()) % 7)
rangeEnd = rangeEnd - datetime.timedelta((rangeEnd.isoweekday() + 7 - endDay) % 7)
return (rangeEnd - rangeStart).days // 7 + 1
rangeStart = datetime.date(2017, 8, 3)
rangeEnd = datetime.date(2017, 9, 15)
startDay = 4
endDay = 7
result = count(rangeStart, rangeEnd, startDay, endDay)
print(result)

calculate elapsed time in flash

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);
}

Resources