I'm trying to time a ajax request, but I get random elapsed time:
startTime = new Date();
$.ajax({
...
success: function(response){
endTime = new Date();
timeDiff = endTime - startTime;
elapsed = Math.round(timeDiff % 60);
alert(elapsed + ' seconds elapsed');
}
}
...Like after 2 seconds I get 36 seconds, or 59 seconds, or 1 second etc..
What am I doing wrong here?
Use / instead of %
% is modulo operator.
Proper code to calculate number of seconds between to dates:
(endTime.getTime() - startTime.getTime()) / 1000
Date - Date returns milliseconds. Lets say your request takes one second, so timediff = 1000. You then do a 1000 % 60, which is 40 and not what you want...
I think you want this:
elapsed = Math.round(timeDiff / 1000);
Which will convert milliseconds to seconds.
The modulo operator % return the remainder of a division operation which is not something you appear to be after...
http://en.wikipedia.org/wiki/Modulo_operation
Add a + sign to both versions of new Date():
startTime = +new Date();
That will guarantee that the date is converted into a numerical value (timestamp) which you can do the substraction operation with. It looks like it does work without, but I don't know what that will do some in browsers/versions implementations.
Also as mentioned in other answers, you need to divide the result (which is in miliseconds) by 1000 to get the seconds.
Related
I apologise in advance for being a complete dunce but these are in fact my very first shaky steps into trying to get something done with Javascript and I feel somewhat lost and confused.
I have the following float: 53.93
This decimal value represents minutes and seconds and it comes from multiplying the longitude I get from the web-browser´s Geolocation API times four (x4). I have this value stored in a variable which I want to convert into minutes and seconds so that I can then add it to the current UTC time so that I can get a new HH:MM:SS time on screen with the added difference(current UTC Time + 53 minutes and 93 seconds.)
I understand that I should first convert times into milliseconds in order to be able to calculate the time difference but I'm stuck at converting the float into minutes and seconds (or should I convert it directly into milliseconds?)
Thank you kindly.
JavaScript's Date works in milliseconds, so if you have a number representing minutes (whether or not including fractional minutes), you can convert that to milliseconds by multiplying it by 60 (to get seconds) and 1000 (to get milliseconds), e.g., multiply by 60,000. But, you've said you have the value 13.48 and later in the text of your question you've said "...current UTC Time + 13 minutes and 48 seconds..." Those are two different things. .48 of a minute is roughly 28.79 seconds, not 48 seconds. So if you really mean that the figure 13.48 is supposed to mean 13 minutes and 48 seconds, the calculation is more compliated:
const value = 13.48;
const wholeMinutes = Math.trunc(value);
const milliseconds = (wholeMinutes * 60 + (value - wholeMinutes)) * 1000;
You can get the current date/time via Date.now(), which gives you milliseconds since The Epoch UTC (Jan 1st 1970 at midnight).
You can create a Date instance from a given milliseconds-since-The-Epoch value via new Date(value).
So if 13.48 represents fractional minutes (13 minutes and roughly 28.79 seconds):
const minutes = 13.48;
const nowPlusThoseMinutes = new Date(Date.now() + (minutes * 60000));
Live Example:
const minutes = 13.48;
const now = Date.now();
const nowPlusThoseMinutes = new Date(now + (minutes * 60000));
console.log(nowPlusThoseMinutes);
console.log(`now = ${new Date(now)}`);
console.log(`nowPlusThoseMinutes = ${nowPlusThoseMinutes}`);
(The () around minutes * 60000 aren't necessary, the * will happen before the + either way because of operator precedence, but they can help make your intent clear to human readers.)
But you mean it to mean 13 minutes and 48 seconds:
const value = 13.48;
const wholeMinutes = Math.trunc(value);
const milliseconds = (wholeMinutes * 60 + (value - wholeMinutes)) * 1000;
const nowPlusValue = new Date(Date.now() + milliseconds);
Live Example:
const value = 13.48;
const wholeMinutes = Math.trunc(value);
const milliseconds = (wholeMinutes * 60 + (value - wholeMinutes)) * 1000;
const now = Date.now();
const nowPlusValue = new Date(now + milliseconds);
console.log(`now = ${new Date(now)}`);
console.log(`nowPlusValue = ${nowPlusValue}`);
I'm trying to get a difference between two dates in seconds. The logic would be like this :
set an initial date which would be now;
set a final date which would be the initial date plus some amount of seconds in future ( let's say 15 for instance )
get the difference between those two ( the amount of seconds )
The reason why I'm doing it it with dates it's because the final date / time depends on some other variables and it's never the same ( it depends on how fast a user does something ) and I also store the initial date for other things.
I've been trying something like this :
var _initial = new Date(),
_initial = _initial.setDate(_initial.getDate()),
_final = new Date(_initial);
_final = _final.setDate(_final.getDate() + 15 / 1000 * 60);
var dif = Math.round((_final - _initial) / (1000 * 60));
The thing is that I never get the right difference. I tried dividing by 24 * 60 which would leave me with the seconds, but I never get it right. So what is it wrong with my logic ? I might be making some stupid mistake as it's quite late, but it bothers me that I cannot get it to work :)
The Code
var startDate = new Date();
// Do your operations
var endDate = new Date();
var seconds = (endDate.getTime() - startDate.getTime()) / 1000;
Or even simpler (endDate - startDate) / 1000 as pointed out in the comments unless you're using typescript.
The explanation
You need to call the getTime() method for the Date objects, and then simply subtract them and divide by 1000 (since it's originally in milliseconds). As an extra, when you're calling the getDate() method, you're in fact getting the day of the month as an integer between 1 and 31 (not zero based) as opposed to the epoch time you'd get from calling the getTime() method, representing the number of milliseconds since January 1st 1970, 00:00
Rant
Depending on what your date related operations are, you might want to invest in integrating a library such as day.js or Luxon which make things so much easier for the developer, but that's just a matter of personal preference.
For example in Luxon we would do t1.diff(t2, "seconds") which is beautiful.
Useful docs for this answer
Why 1970?
Date object
Date's getTime method
Date's getDate method
Need more accuracy than just seconds?
You can use new Date().getTime() for getting timestamps. Then you can calculate the difference between end and start and finally transform the timestamp which is ms into s.
const start = new Date().getTime();
const end = new Date().getTime();
const diff = end - start;
const seconds = Math.floor(diff / 1000 % 60);
Below code will give the time difference in second.
import Foundation
var date1 = new Date(); // current date
var date2 = new Date("06/26/2018"); // mm/dd/yyyy format
var timeDiff = Math.abs(date2.getTime() - date1.getTime()); // in miliseconds
var timeDiffInSecond = Math.ceil(timeDiff / 1000); // in second
alert(timeDiffInSecond );
<script type="text/javascript">
var _initial = '2015-05-21T10:17:28.593Z';
var fromTime = new Date(_initial);
var toTime = new Date();
var differenceTravel = toTime.getTime() - fromTime.getTime();
var seconds = Math.floor((differenceTravel) / (1000));
document.write('+ seconds +');
</script>
Accurate and fast will give output in seconds:
let startDate = new Date()
let endDate = new Date("yyyy-MM-dd'T'HH:mm:ssZ");
let seconds = Math.round((endDate.getTime() - startDate.getTime()) / 1000);
time difference between now and 10 minutes later using momentjs
let start_time = moment().format('YYYY-MM-DD HH:mm:ss');
let next_time = moment().add(10, 'm').format('YYYY-MM-DD HH:mm:ss');
let diff_milliseconds = Date.parse(next_time) - Date.parse(star_time);
let diff_seconds = diff_milliseconds * 1000;
let startTime = new Date(timeStamp1);
let endTime = new Date(timeStamp2);
to get the difference between the dates in seconds ->
let timeDiffInSeconds = Math.floor((endTime - startTime) / 1000);
but this porduces results in utc(for some reason that i dont know).
So you have to take account for timezone offset, which you can do so by adding
new Date().getTimezoneOffset();
but this gives timezone offset in minutes, so you have to multiply it by 60 to get the difference in seconds.
let timeDiffInSecondsWithTZOffset = timeDiffInSeconds + (new Date().getTimezoneOffset() * 60);
This will produce result which is correct according to any timezone & wont add/subtract hours based on your timezone relative to utc.
Define two dates using new Date().
Calculate the time difference of two dates using date2. getTime() – date1. getTime();
Calculate the no. of days between two dates, divide the time difference of both the dates by no. of milliseconds in a day (10006060*24)
const getTimeBetweenDates = (startDate, endDate) => {
const seconds = Math.floor((endDate - startDate) / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
return { seconds, minutes, hours, days };
};
try using dedicated functions from high level programming languages. JavaScript .getSeconds(); suits here:
var specifiedTime = new Date("November 02, 2017 06:00:00");
var specifiedTimeSeconds = specifiedTime.getSeconds();
var currentTime = new Date();
var currentTimeSeconds = currentTime.getSeconds();
alert(specifiedTimeSeconds-currentTimeSeconds);
I'm trying to compare to 2 dates by hour/minutes/seconds, in order to make a script to resume a script when closed. If current time is pass closed time + interval ( currently set at 30 minutes) should execute and run the script normally, if not wait till difference timeouts to execute.
Current hour/minutes/seconds is not a must but the result should be in ms interval
Example:
interval = (30 * 60 * 1000)
close time = 15:10:53
current time = 15:15:29
close time + interval = 15:40:53
first time I check if `current time` <= `close time + interval`
then calculate `difference`
`difference` = (close time + interval = 15:40:53) - (current time = 15:15:29)
Result should be setTimeout(function(){ alert("Hello"); }, time difference);
The only way I'm thinking of doing this is calculate each difference from Hour,Minutes,Seconds and then finding out the ms for setTimeout
I tried but results were weird, not something that would count as smaller than 30min
var ONE_S = 1000 ;
var timeDiff = Math.abs(closeTime - currentTime);
var diffS = Math.round(timeDiff/ONE_S)
Use Date objects and compare timestamps like so:
var interval = 30 * 60 * 1000;
var closeTime = new Date('Wed Nov 26 2015 10:17:44 GMT-0400 (AST)');
var currentTime = new Date;
var difference = (closeTime - currentTime) + interval;
if(difference < 0) {
console.log('time has expired');
}else{
setTimeout(someFunction, difference);
}
closeTime - currentTime gets the time between timestamps in ms, which will be negative if it's past closing time. We offset closing time by 30 minutes (by adding interval). Then we just have to check if difference < 0 to know if time has expired, and if not we can wait difference milliseconds to trigger someFunction
Currently I am working on JavaScript, jQuery, HTML5 to improve myself. I have a opensourcely coded clock, which I have converted it into a counter (reverse counter).
Problem I am having is, in my setInterval(){...} I have four variables -> second,min,hour, and day. The problem is, when I get the seconds, I get something like 1.155, 2.312, 3.412 (seconds).
My setInterval function is below
setInterval(function(){
//var duration = parseInt(Date.now() /1000 ) - 1365470000;
var futureTime = Date.parse('April 10, 2013 22:00:00');
var duration = (( parseInt(Date.now() - futureTime ) / 1000));
var seconds = duration % 60;
duration = parseInt(duration / 60);
var minutes = duration % 60;
duration = parseInt(duration / 60);
var hours = (duration)%24;
duration = parseInt(duration / 24);
var days = duration % 365;
animation(gVars.green, seconds, 60);
animation(gVars.blue, minutes, 60);
animation(gVars.orange, hours, 24);
animation(gVars.red, days, 365);
},1000);
}
And my output is below for some random time since i use parseInt(Date.now()).
I have to give the link since I don't have enough rep.
http://i.stack.imgur.com/0Zkbi.png
How can I get rid of the decimal point in setInterval(){} functions?
Thanks in advance.
JavaScript offers more convinient API to work with date and time in order to fetch seconds, minutes, hours and days. Try this code:
var duration,
seconds,
minutes,
hours;
duration = new Date((new Date('April 11, 2013 23:00:00')) - (new Date()));
seconds = duration.getSeconds();
minutes = duration.getMinutes();
hours = duration.getHours();
Now you will have integer values in all 4 variables above, without any decimal point.
var seconds = 1234.13;
var seconds = seconds + '';
seconds = seconds.split('.')[0];
console.log(seconds);
I want to make a function either using pure Javascript or also benefiting from jquery to count down to an ending time such as:
//consumes a javascript date object
function countDown(endtimme){
...
}
and it should display in html such as
<div id="time_left_box">
<h1>Time remaining</h1>:
<p>hours left: ..remaining day will be here## <p>
<p>minutes left: ##remaining day will be here## <p>
<p>seconds left: ##remaining day will be here## <p>
</div>
Indeed and it would be even more great if it can refresh itself every second.
I am very naive with javascript and confused about how to approach, any help would be appreciate.
You could use jQuery Countdown
Take a look at this one: http://keith-wood.name/countdown.html
It can be done in JavaScript without plugins.
You need to get the current date time, down to the denominator that is one smaller than what you are displaying. With your example, this would mean you need to get everything down to milliseconds.
var currentTime = new Date(n.getFullYear(), n.getMonth(), n.getDate(), n.getHours(), n.getMinutes(), n.getSeconds(), n.getMilliseconds());
You then find the difference between now and the desired time. This is given to you in milliseconds.
var diff = endtime - currentTime;
Because this is returned in milliseconds you need to convert them into seconds, minutes, hours, days etc... This means establishing how many milliseconds are in each denominator. Then you are able to use mod and divide to return the number needed for each unit. See below.
var miliseconds = 1;
var seconds = miliseconds * 1000;
var minutes = seconds * 60;
var hours = minutes * 60;
var days = hours * 24;
var years = days * 365;
//Getting the date time in terms of units
//Floored so that they go together (to get just year/days/hours etc.. by themselves you need to use Math.round(diff/desired unit);
var numYears = Math.floor(diff / years);
var numDays = Math.floor((diff % years) / days);
var numHours = Math.floor((diff % days) / hours);
var numMinutes = Math.floor((diff % hours) / minutes);
var numSeconds = Math.round((diff % minutes) / seconds);
Once you have the denominators you want to display you can return this to the html page through different methods. For example:
document.getElementById("tyears").innerHTML = numYears;
That sums up your method. However, to make it run on a set interval (which is why you update the HTML display within the JavaScript function) you need to call the following function, giving your function name and provide your interval in terms of milliseconds.
//Call the count down timer function every second (measured in miliseconds)
setInterval(countDown(endtime), 1000);