I have a countdown timer in javascript. It has two variables. Both store current dates. One variable (currentDate) is converted to milliseconds and then milliseconds according to 10 minutes is added. Other variable (d) stores current datetime in a function that is run every second. That function takes difference between these two and displays in seconds. That works. Below is the code.
<script>
var currentDate = new Date();
var d =new Date();
var tl = currentDate.setTime(currentDate.getTime() + 2*60*1000);
var seconds =(tl - d)/1000;
function secondPassed() {
var minutes = Math.round((seconds - 30)/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('bonus').innerHTML = "Buzz Buzz";
} else {
seconds--;
}
}
var countdownTimer = setInterval('secondPassed()', 1000);
</script>
But problem is that every time I refresh the page, the countdown starts again from 10 minutes. I want to store a particular datetime (TIMESTAMP) in php (which will be stored when user visits the page). Then I will add 10 minutes to that and that datetime will be taken as reference in javascript to subtract current timestamp from.
So basically I need to convert php datetime (TIME_STAMP) to milliseconds, give that to javascript, add milliseconds according to 10 minutes to it, and subtract milliseconds corresponding to current datetime to get remaining time in the function.
The gettime method in javascript uses 1970-01-01 00:00:00 as refernce to convert into milliseconds. So, in short I need to get milliseconds between that and the stored datetime(TIMESTAMP). How can I do it?
I need to do this in php, not MySQL, so this question : MYSQL - datetime to seconds does not help me.
EDIT : I am storing date as TIMESTAMP in MySQL.
Use PHP's time function to get seconds since the epoch:
Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
http://us3.php.net/time
It's not completely clear to me from your question how you're storing the time stamp in the DB, but if it's a MySQL DATETIME, when you select it from the DB use SELECT UNIX_TIMESTAMP(time_col) to convert it to seconds since the epoch on the fly. Now you're dealing with UNIX timestamps in all cases.
UNIX_TIMESTAMP docs here
Related
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)
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)
I have a functie that keeps track of the local time live. I'm using the new Date(); object to get the local hours, minutes and seconds.
I also want the user to give a input where a function has to start on a specific time. The input of the user is a string (I don't want the user to work with the Date(); object as not all users can program). For example:
Input user:
var timeStart = "10:08:30";
Live time converted to string:
var sTime = todayHours + ':' + todayMinutes + ':' + todaySeconds;
When the two are equal:
if(sTime == timeStart )
{
//function when equals time
//This function has a timeout, so it will run infinite times
var timeOutId = setTimeout(function()
{
//call functie
}, 10000); //every 10 seconds as example
}
Alright this work just fine. I can compare strings only if they are the same or not. However to make it a little bit more complicated: I also want the user to give a end time, when to function has to stop:
Input user:
var timeEnd = "11:08:30";
Live time converted to string:
var sTime = todayHours + ':' + todayMinutes + ':' + todaySeconds;
When the two are equal:
if( sTime == timeEnd)
{
//function when equals time
//calls the timeout id and stops it
clearTimeout(timeOutId);
}
Now this just works fine! However now you know what i'm trying to do i'm wondering if i can do in some way:
if(sTime >= timeStart && sTime <= timeEnd)
{
//timeout will only be set when it's in between the given time
setTimeout(function()
{
//call functie
}, 10000); //every 10 seconds as example
}
Question
I there a way i can transform my string time(using 2-digits method) in a excisting date time so i can compare it on time?
My time only uses [hour, minutes and seconds], which causes problems as the Date(year, month and day) is not defined.
I've tryed to use Momentjs but it also refuses to work with only hour, minutes and seconds. Or i might not be farmilier on how to do this.
The method i want to use seems much easier as i don't have to define when to cancel the timeOut.
Any help is appreciated!
P.s What i actually just have to accomplish is converting the string time to a unix time stamp (Of course other methods are welcome too).
Dont know moment.js but you could still use basic parseInt to extract the time , turn it into and integer so you can compare it with another one :
function stringtime_to_seconds(aString){
var time,a = aString.split(":");
switch(a.length){
default: // 3 , you'll need to handle other cases
time = parseInt(a[0])*3600+parseInt(a[1])*60+parseInt(a[2]);
}
return time;
}
then you can compare dates.
I've tryed to use Momentjs but it also refuses to work with only hour, minutes and seconds. Or i might not be farmilier on how to do this.
...
What i actually just have to accomplish is converting the string time to a unix time stamp
You simply need to provide the format string, such as:
// parse the input
var timeStart = "10:08:30";
var m = moment(timeStart,"HH:mm:ss");
// then one of these
var s = m.unix(); // unix time in seconds
var ms = m.valueOf(); // unix time in milliseconds
Of course, to get unix time you have to have a specific date in mind. With the above method, it will use the local time zone's "today". This might be a concern if you have a range that spans over midnight, such as 10pm - 2am, so you might need to adjust.
Also, you said you were doing a range comparison like:
if(sTime >= timeStart && sTime <= timeEnd)
You probably should not do that with strings. But also, you should use a half-open interval [start,end). In other words:
if(sTime >= timeStart && sTime < timeEnd)
Usually when someone says 1:00 to 2:00, they mean that the range is over at 2:00.
I am experiencing some unexpected results with a GMT time zone offset calcultaion.
I am using the ExtJS date class to help calculate the time that a message arrives from the server at GMT 0 to the user's local machine which is currently GMT +8.
I thought that if i calculated the offset, then added that to the timestamp in seconds then i could use the following calculation to give me a string to format as i please.
var d = new Date((stamp + offset) * 1000);
stamp is the date/time in seconds as is the offset.
This returns the current date and time at my location but plus 8 hours. If i do not add the offset then the time is correct.
Does the method new Date() automatically give me the date/time at local time?
Just adding this in case it helps others looking latter. May be wrong but works for what I needed.
I have the user's offset stored in seconds.
offset assumed in seconds change the (offset * 1000) to make sure offset gets converted to milliseconds if your offset not in seconds.
function offsetDate(offset){
var d = new Date(new Date().getTime() + (offset * 1000));
var hrs = d.getUTCHours();
var mins = d.getUTCMinutes();
var secs = d.getUTCSeconds();
//simple output
document.write(hrs + ":" + mins + ":" + secs);
just insert a unix timestamp containing the thousandth of a second.
that unix timestamp should be UTC 0 and javascript will look up the local timezone of the clients computer and will calculate it.
as you can see behind this link, there are some UTC methods wich give you the time without local time offset. maybe this might be what you search for (in case you really want to set the timezone yourself).
edit:
new Date().getTimezoneOffset() will show you the difference between the local timezone and utc but you should consider using the utc methods.
From the looks of it, stamp is your local time including timezone offset. JavaScript has no knowledge of the timezone of the server, it's (mainly) a client-side language.
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);
}