Calculate amount of time until the next hour - javascript

I'm working on a busing website project and the buses run every hour. I'm having trouble creating a widget that finds the time between now and the next hour, so that it is clear when the next bus will run. My client requires that it is in javascript. Any suggestions?
Thanks in advance.

To know exactly the miliseconds from now to the next hour:
function msToNextHour() {
return 3600000 - new Date().getTime() % 3600000;
}
Please note that this will strictly tell you how many milliseconds until the NEXT hour (if you run this at 4:00:00.000 it will give you exactly one hour).

function getMinutesUntilNextHour() { return 60 - new Date().getMinutes(); }
Note that people who's system clocks are off will miss their bus. It might be better to use the server time instead of the time on the client's computer (AKA at least partly a non-client-side-javascript solution).

you have the Date object in Javascript, you could do something like:
var now = new Date();
var mins = now.getMinutes();
var secs = now.getSeconds();
var response = "it will be " + (60 - mins - 1) + " minutes and " + (60 - secs) + " seconds until the next bus";
of course you will have to work more on those calculations, but that's how you work with time in javascript

Either of the other two answers will work well, but are you aware of the docs available to you about all the other nice things date is JS can do for you?
Mozilla Date Docs
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date

Lots of answers, a really simple function to get the rounded minutes remaining to the next hour is:
function minsToHour() {
return 60 - Math.round(new Date() % 3.6e6 / 6e4);
}

Related

How to add time to time (minutes + minutes) in Javascript ? (Not to Date)

I don't finde anywhere how to add time to time, like adding 45 minutes to 45 minutes and having 1:30 (1 hour, 30 minutes).
I just find how to add time to actual Date.
Heres an example in PHP of what I'm looking for:
$seconds_toadd = 45;// VALUE TO GET FROM A TEXTBOX
$actual_value = '00:45'; //45 minutes, 0 hours is the actual value
$resultado = new DateTime($lectura_xml);
$resultado->add(new DateInterval('PT' . $seconds_toadd . 'S'));//This is how I add seconds in PHP
$stamp = $resultado->format('I:s');//Formatting result
echo $stamp;
Thank you.
Moment.js is a great library for date/time handling in JavaScript and better than the standard API and any homemade solution in many aspects.
Very simple but similar use case from their docs:
var a = moment.duration(1, 'd');
var b = moment.duration(2, 'd');
a.add(b).days(); // 3

Get difference In minute of two dates

I Want to get difference in minutes of two dates, Meaning-
var diff= Current_Date- Date_Abc
and diff should in minutes.
What I want to do.
I have a GPS device And its get reporting every 30 second. If this device stop reporting from 90 minutes than I want to get stop flag for this.
In reporting information there is date Time "2017-06-21 12:55:21" in this format.
So I want to check If(CurrentDate-ReportedDateTime>=90) then DeviceStoped= true else DeviceStoped=false.
How do this in ext JS or in Java script
If your dates are timestamps or instances of Date, you can try the following:
const ONE_MINUTE_IN_MILLISECONDS = 1000 * 60,
diff = (currentDate - pastDate) / ONE_MINUTE_IN_MILLISECONDS;
So it's very straightforward, you can easily calculate the difference in milliseconds, then you just need to convert it to minutes.
Get the milliseconds of both the dates and compare the difference with 90 minutes (5,400,000 ms).
var diffMs = (Date_Abc- Current_Date); // milliseconds between Date_Abc &
Current_Date
var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes
To discard the seconds.
diffMins = Math.floor(diffMins)

Jquery Countdown To Next Wednesday 11pm

I need to write a function that will take a javascript date object in UTC time. It needs to find the difference in seconds from the given date and next (or coming) Wednesday 11pm then put it in a countdown object. Once the the timer hits 0, I need it to restart again. I know I have to use the getDay() function somehow but I'm unsure of how to go about this.
Logic and Code
You don't need jQuery for the countdown timer itself. The date object is part of plain vanilla JavaScript.
For UTC, you'll want to use the getUTCDay() method.
Assuming givenDate is a Date object, the following would calculate how many days until the coming Wednesday (day 3).
var daysUntilTarget = (3 - givenDate.getUTCDay() + 7) % 7;
If given date is on a Wednesday, the above will return 0 and you'll need to determine if target time has passed yet. You could use something like this:
var daysUntilTarget,
targetDay = 3,
targetHour = 23,
targetMinute = 0,
targetSecond = 0;
if (
targetDay == givenDate.getUTCDay() &&
targetHour * 3600 +
targetMinute * 60 +
targetSecond * 1 <
givenDate.getUTCHours() * 3600 +
givenDate.getUTCMinutes() * 60 +
givenDate.getUTCSeconds() * 1 +
givenDate.getUTCMilliseconds() / 1000
) {
//given date is after target time on target day
daysUntilTarget = 7;
}
Use the setUTCDate() and setUTCHours methods to set the target date and time.
var targetDate = new Date(givenDate);
targetDate.setUTCDate(givenDate.getUTCDate() + daysUntilTarget);
targetDate.setUTCHours(targetHour, targetMinute, targetSecond);
Use the getTime() method to get a timestamp for both the given date and the target date. Then you can calculate the difference between these and divide by 1000 to get the number of seconds.
var countdownSeconds = (targetDate.getTime() - givenDate.getTime()) / 1000;
The following will convert the total seconds into days, minutes, and seconds. You can then write these to an element in your HTML.
var daysLeft, hoursLeft, minutesLeft, secondsLeft;
secondsLeft = parseInt(countdownSeconds);
daysLeft = parseInt(secondsLeft / 86400);
secondsLeft = secondsLeft % 86400;
hoursLeft = parseInt(secondsLeft / 3600);
secondsLeft = secondsLeft % 3600;
minutesLeft = parseInt(secondsLeft / 60);
secondsLeft = parseInt(secondsLeft % 60);
Be sure to convert countdownSeconds to an integer before doing further calculations with it. Otherwise, you may get undesired results due to floating point math. For example,
0.009 / 86400 = 1.0416666666666665e-7;
parseInt(1.0416666666666665e-7) = 1;
parseInt(0.009 / 86400) = 1; //probably not what you were expecting
Countdown Timer
To update the timer, you could decrement a counter or use the client machine's clock to keep time.
The counter method is not as accurate as the clock method because the former doesn't take into account the amount of time it takes for the code to run. I've noticed a 3-second loss over a half-hour period. Adjusting the loop interval will not fix this since different browsers run code at different speeds. And code may run slower for other reasons such as when machine is low on memory.
The client machine's time may not be accurate to begin with. However, the server time can be compared to the client time initially to calculate an offset. Then the client time can be used as a counter rather than an absolute value. The draw back is that if the client time changes, it will affect the countdown. Note that time zone changes and changes due to Daylight Saving Time will not affect the countdown since they do not affect the timestamp.
Examples
I've created two fiddles using the code described above.
Countdown Timer (Using Counter)
Countdown Timer (Using Clock)

Increment a var by one every 24 hours from a specific date

I've never used Javascript before (or any other programming language) so sorry for asking this question because im sure it's very simple.
What I want to do is set a date in Javascript, then increment it by one every 24 hours. So three days after the date is set, 3 is displayed in the HTML (not the date itself). And after 100 days, 100 is displayed.
Thank you.
You have to create two date objects, one representing your initial date, and another one representing right now. Then, calculate the difference:
// Calculate days since Dec 1st 2012
var initialDate = new Date(2012, 11, 1); // Attention: month is zero-based
var now = Date.now();
var difference = now - initialDate;
var millisecondsPerDay = 24 * 60 * 60 * 1000;
var daysSince = Math.floor(difference / millisecondsPerDay);
alert(daysSince); // 80
http://jsfiddle.net/PmYFc/
If you are looking to show how many days the page has been open, you want to use the setInterval function: https://developer.mozilla.org/en-US/docs/DOM/window.setInterval.
So, if your HTML element looked like <span id='example'>0</span>, your JS might look like this:
var date = 0,
element = document.getElementById("example");
setInterval(function(){
date++;
element.innerText = date;
}, 1000 * 60 * 60 * 24); //milliseconds, seconds, minutes, hours
Though, it seems unlikely any page would sit unrefreshed for any significant length of time. If you need to persist the date variable beyond page refreshes you could look into localstorage.

Live asynchronous time feed for websites

I want to show up the time over my website based over the location of the user, let’s say if user one browsing the website is from USA than the time should be what is in USA currently and same for China etc. and all.
I was wondering if there exists a JavaScript plugin for it but I didn’t find any as dynamic as I want, my requirements include:
Something that can be fully stylized according to website theme (no iframes)
The pattern I want is to be in (HH:MM:SS)
It should be asynchronous like the second [SS] keep ticking and the time keep updating
Is this possible, a way around to achieve it?
Wouldn't this be enough?
html
<span id="time"></span>
js
$(function() {
var time = $("#time");
function getTime() {
var now = new Date(),
hours = now.getHours(),
minutes = now.getMinutes(),
seconds = now.getSeconds();
return (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds);
}
setInterval(function() {
time.text(getTime());
}, 1000);
});​
Example
Just putting out the local system time of the user isn't enough?
If you want a server based solution, please take a look at the solution here. You have to find out the users timezone first and then manipulate the server time with an offset from the timezone using $dt->setTimezone(new DateTimeZone("Europe/Berlin"));.

Categories

Resources