I am making a website for a limo service that should provide the price for the service you are requesting beforehand.
The regular service is 1$ a minute. However, all the time from mid-night to 8am, is considered premium and it costs 2$.
Now, here is the complicated part. I need to isolate how much time the client is paying on regular time and on premium, in order to generate the price.
For example. If the service is from 9pm to 2am, the client pays 3 hours at 1$/min and 2 hours at 2$/min.
How to I get the 9pm and 2am, and convert to 180minutes+120minutes?
Btw, I tied tampering with http://code.google.com/p/datejs/. But it just was not working. Is there a smart "math" way of doing this?
Thanks for the help guys :)
So premium time is all in the A.M. it seems and non is all in the P.M. so just subtract whatever time they give that's pm from 12, in your example 12-9 and you get 3hours, then add any hours to 0 for the am, again your example 0+2 which is of course 2 hours. Then times by 60 to get the minutes. Once you have that times each amount by the amount its being charged and add them together. I would have the am/pm be a toggle that sets a variable to true/false for each.
code could look something like this:
//start_time and end_time are objects that have 2 properties, am/pm
//which is a bool and time which is a int
function calc_time(start_time,end_time){
var normal_pay;
var premium_pay;
if(start_time.pm == true){
normal_pay = 12 - start_time.time;
normal_pay = normal_pay * 60;
} else{
normal_pay = 0 + start_time.time;
normal_pay = normal_pay * 60 * 2; //this is premium time the whole night was premium pay
}
if(end_time.am == true){
premium_pay = 0 + end_time.time;
premium_pay = premium_pay * 60 * 2;
} else {
premium_pay = 12 - end_time.time;
premium_pay = premium_pay * 60; //this is normal time the whole night was normal pay
}
return premium_pay + normal_pay;
}
This doesn't solve everything you still have to account for things like minutes, say they want to end at 3:25am but that's not that hard.
Related
Is it possible to display the highest expanded whole number metric time with Javascript code,
For an application, I want to display a time but instead of having a set metric (hour, min or second) it's flexible and I want to display the highest expanded metric given a time value. The input would be in seconds, and if there's a value that exceeds 3 digits I want it to be converted to the next unit, so for example
Input: 1500s
Output: 25mins
Reason: In its most expanded form it would be 25mins
Input: 3245155s
Output: 90hrs
Reason: In its most expanded form it would be 90hrs because in mins it would be 5409 which exceeds my 3 digit limit for a whole number.
Input: 34s
Output: 34s
Reason: In its most expanded form it would remain 34s as it is still within my 3 digit range
I know it's possible to write an algorithm for this, but instead of reinventing the wheel I'd just like to know if this functionality is built-in Javascript
This is the solution that works for me, dividing the various units (therefore converting) until I reach the final unit I'd use.
const timeFormatter = (seconds) => {
if (!seconds) return "0s";
if (seconds < 60) return `${seconds}s`;
let minutes = Math.round(seconds / 60);
if (minutes < 60) return `${minutes}min`;
let hours = Math.round(minutes / 60);
if (hours < 24) return `${hours}hr`;
let days = Math.round(hours / 24);
return `${days}d`;
};
I'd like to know if there is a way to show scheduled pop up windows, say you're hosting a virtual conference at 6pm, and you want to warn your users an hour early by showing a pop up window at 5pm with a messagge like "Main conference starts in one hour".
This is for a webpage intended to work on desktop and mobile, thus I'm working on HTML and javascript.
Haven't code anything yet, I'm rather looking for a starting point.
Appreciate the help.
So based on what you just said, I think that the following js code will solve your issue, however, since I don't know what is your current environment, you will have to change the code to your needs:
// Always use a 24 hour format with this implementation.
function scheduleDailyConferences(timeArray) {
const offset = 60; // alert offset (1h prior in minutes)
const now = new Date();
const current = now.getHours() * 60 + now.getMinutes();
for (let time of timeArray) {
let tot = time.h * 60 + time.m - offset;
if (tot < current) continue;
tot -= current;
setTimeout(() => {
alert(`Your meeting starts in ${offset} minutes.`);
}, tot * 60 * 1000);
}
}
// assuming the following conferences of the day:
scheduleDailyConferences([
{ h: 13, m: 45 } // 1:45 pm
{ h: 4, m: 00 } // 4:00 pm
]);
Basically, given a time table timeArray in a human readable format, it reads every entry, subtracts a given offset of 1 hour and figures out when to fire an alert.
If the meeting has already ended or begun, it doesn't fire an alert (but you can easily change that).
I am working on a simple Timesheet app, I am trying to implement an auto calculator that will sum up your hours for each day (Sunday, Monday, Tuesday, etc ...). A problem I noticed is that in some cases, users will enter activities that will be within the same date time periods.
For example:
$scope.Example = [
{Description:"Example activity",Start:"2018-06-24 8:00",End:"2018-06-24 10:00",Total:2},
{Description:"Example activity2",Start:"2018-06-24 9:00",End:"2018-06-24 10:00",Total:1},
{Description:"Example activity3",Start:"2018-06-24 10:00",End:"2018-06-24 11:00",Total:1}];
$scope.Calculate_all_entries = function(){
$scope.Total.Sunday = 0;
if($scope.Example){
angular.forEach($scope.Example, function(element){
if(moment(element.Start).format("dddd") === "Sunday"){
$scope.Total.Sunday = $scope.Total.Sunday + element.Total;
}
})
}
}
In this case the total should be 3 hours and not 4 hours as we dont charge for work within the same hours. I'm need to implement a system that would check if the dates are within the same period and provide the appropriate total.
I found this in the documentation on momentjs that seemed to be close to what i need but only takes one value:
moment('2010-10-19 11:00').isBetween('2010-10-19 10:00', '2010-10-25 00:00'); // true
Would anyone know of any other methods to check wether or not the start and end time are in the same period as other entries in the same day?
Sure, you can use momentjs's unix() function to convert those date times to an integer which then can easily be used to check whether the timestamp is in between two other timestamps.
Here is an example:
var timeToCheck = moment('2010-10-19 11:00').unix();
var startTime = moment('2010-10-19 10:00').unix();
var endTime = moment('2010-10-25 00:00').unix();
console.log(timeToCheck >= startTime && timeToCheck <= endTime); // true
So there's plenty of examples on how to calculate the time between two dates.
But in my case, I have a date X. Let's say it's today.
X has a time associate to it, e.g. 08:00 (Or what I get back from .getHours())
I need to know if the hours of X are between a start hour (say "07:00") and an end hour (say "12:00")
X will be always retrieved via getHours()
The start and end hour of the range have a fixed format (e.g. "07:00" and "12:00")
Performance is an issue, so whatever performs better is preferred (e.g. if it implies using moment, that's fine, but if a custom function would perform better, we want that)
My first approach would be, as the formats are fixed, to transform the .getHours() to a number, likewise for the range hours, and then calculate...I feel this approach my have trouble with some special cases I may not be aware of?
You could use moment-range
From docs:
You can also create a range from an ISO 8601 time interval string:
var timeInterval = "2015-01-17T09:50:04+00:00/2015-04-17T08:29:55+00:00";
var range = moment.range(timeInterval);
range.contains(X); // true if between interval
If you want to check part hours, consider converting the hours to minutes, something like the following. How will you deal with ranges that go over midnight? e.g. 23:30 to 01:30.
/* Determine if the current time is between two provided hours
** #param {string} h0 - time in format h:mm
** #param {string} h1 - time in format h:mm
** #returns {boolean} true if the current time is between or equal to h0 and h1
*/
function betweenHours(h0, h1) {
var now = new Date();
var mins = now.getHours()*60 + now.getMinutes();
return toMins(h0) <= mins && mins <= toMins(h1);
}
/* Convert hours to minutes
** #param {string} h - time in format h:mm
** #returns {number} time converted to minutes
*/
function toMins(h) {
var b = h.split(':')
return b[0]*60 + +b[1];
}
<form>
Start time (h:mm)<input name="startHours">
<br>
End time (h:mm)<input name="endHours">
<br>
<button type="button" onclick="
this.form.inRange.value = betweenHours(this.form.startHours.value, this.form.endHours.value);
">Check range</button>
<br>
Currently in range? <input name="inRange" readonly>
</form>
Are you dealing with military tine? (From 0:00 to 24:00)
getHours() returns an Integer, and if you are only interested in hours and not minutes, you can use parseInt() to turn the start and end hours into integers as well. For example, parseInt('07:00', 10) will return 7. So if you wanted to create a function to test if the current time is between two hours, it might look something like this:
function isBetweenHours(startHour, endHour)
{
var now = new Date().getHours();
return now >= parseInt(startHour, 10) && now <= parseInt(endHour, 10);
}
Then you would use it like this:
if( isBetweenHours('07:00', '12:00') ) { //some code here }
having a slightly weird issue that I cant figure out. Ive set up a javascript timer, all it does is repeats an interval every second that checks the difference between 2 dates and displays the results. All seems fine, however when leaving the browser open for several minutes (not touching it.. literally walking away for a while), it seems to "time out" and stop functioning. No console error messages or anything, the code just stops executing.. Was wondering if anyone had any idea what could be causing this? Is my code the issue or is this a built in browser function to stop js functions if there is no input from the user on a page for a certain time?
edit sorry should mention this timer is set to run for around 40 days at the moment so it will never realistically meet the clearinterval statement in a user session. The future date variable im adding to the function is a dynamic unix timestamp from PHP for a date which is roughly 40 days in future. Currently set to 1444761301.88
function MModeTimer(futureDate) {
zIntervalActive = true;
var currentTime = new Date().getTime() / 1000;
var timeRemaining = futureDate - currentTime;
var minute = 60;
var hour = 60 * 60;
var day = 60 * 60 * 24;
var zDays = Math.floor(timeRemaining / day);
var zHours = Math.floor((timeRemaining - zDays * day) / hour);
var zMinutes = Math.floor((timeRemaining - zDays * day - zHours * hour) / minute);
var zSeconds = Math.floor((timeRemaining - zDays * day - zHours * hour - zMinutes * minute));
if (zSeconds <= 0 && zMinutes <= 0) {
console.log("timer in negative");
// timer at zero
clearInterval(zTimeInterval);
} else {
if (futureDate > currentTime) {
console.log("timer interval running");
// changes html as part of function
}
}
}
zTimeInterval = setInterval(function() {
MModeTimer(zNewTime)
}, 1000);
This line:
clearInterval(zTimeInterval);
Is clearing the interval when the condition:
if (zSeconds <= 0 && zMinutes <= 0) {
Is met.
And as per the log you've wrote inside, that would be wrong. You are checking that zSeconds and zMinues are less or equal to 0. So when both are 0, the interval will be cleared.
Edit
As per your edits and explanations, may I suggest adding a console log that i'ts not inside any condition?:
function MModeTimer(futureDate) {
console.log('running');
//... rest of your code
That way you can make sure if the interval is running, maybe your conditions are not being TRUE after a while and you won't see any log, but the interval would be still running.