How to set maxTime on my code, i want to display value until 17:00 a clock, and also display all the times in an alert, right now it display only one time and the time.
function() {
var toTime = new Date(result2);
var convertUtctoTime = new Date(toTime.getTime() + toTime.getTimezoneOffset() * 60 * 1000);
var end = new Date(convertUtctoTime);
while (end>=fromTime) {
var newDate = end.setTime(end.getTime()+ 30 * 60 * 1000);
end = new Date(newDate);
alert("Free time at" + " " + end);
}
Instead of checking the date, try checking the time in milliseconds:
while (end.getTime() >= fromTime.getTime()) { ...
Related
I have two variables here (datetime and time)
And I want to add the time to the datetime variable.
var datetime = '2020/09/21 09:33:00';
var time = '00:00:23';
var result = datetime + time; // I know this is wrong
How can I add the two variables so that the result will be
2020/09/21 09:33:23
var date = new Date('2020/09/21 9:33');
var time = 23 * 1000; // in miliseconds
var result = new Date(date.getTime() + time);
So you need to calculate number of seconds and add it to the date
const datetime = '2020/09/21 00:09:33';
const time = '00:00:23';
const parts = time.split(":");
const seconds = +parts[0] * 3600 + +parts[1] * 60 + +parts[2];
const date = new Date(datetime);
date.setSeconds(date.getSeconds() + seconds);
console.log(date.toLocaleString())
Can someone please explain why these 3 different lines that suppose to produce the exact same result, give three different results?
The only accurate one is the 2'nd line (Date.now()). Unfortunately, this is the only one I can't use.
function show_ts_date(idx, ts)
{
var a = new Date(ts * 1000);
var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var year = a.getFullYear();
var month = months[a.getMonth()];
var date = a.getDate();
var hour = a.getHours();
var min = a.getMinutes();
var sec = a.getSeconds();
var formattedTime = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min + ':' + sec ;
alert(idx+'. timestamp: '+ts+' Date: '+formattedTime);
}
var currentdate = new Date();
//line 1: (produces wrong timestamp - it gives the wrong hour (-4) when I convert back to dateTime)
timestamp_1 = Math.floor(new Date(currentdate.getFullYear()+'-'+(currentdate.getMonth()+1)+'-'+currentdate.getDate()+'T'+currentdate.getHours()+':'+currentdate.getMinutes()+':00') / 1000);
show_ts_date(1, timestamp_1);
//line 2 (produces correct timastamp - it gives the correct hour when I convert back to DateTime.)
timestamp_2 = Math.floor(Date.now() / 1000);
show_ts_date(2, timestamp_2);
//line 3 (produces wrong timestamp - it gives the wrong hour (+3) when I convert back to dateTime)
let dat = new Date(Date.UTC(currentdate.getFullYear(), currentdate.getMonth(), currentdate.getDate(), currentdate.getHours(), currentdate.getMinutes(), 00));
timestamp_4 = Math.floor( dat/ 1000);
show_ts_date(4, timestamp_4);
Well, assuming that Date.now() returns the real accurate value (I doubt it is always the case, But that's what I'm left with. you can always convert it back to Date and check if the right date & time came back),
I wrote this function that will compare between the right and wrong timestamps and will add (or decrease) the number of milliseconds from (or to) the false timestamp - turning it in to a correct one:
function getTimestampMilisecondsGap()
{
var currentdate = new Date();
timestamp_1 = Math.floor(new Date(currentdate.getFullYear()+'-'+(currentdate.getMonth()+1)+'-'+currentdate.getDate()+'T'+currentdate.getHours()+':'+currentdate.getMinutes()+':00') / 1000);
//let dat = new Date(Date.UTC(currentdate.getFullYear(), currentdate.getMonth(), currentdate.getDate(), currentdate.getHours(), currentdate.getMinutes(), 00));
//timestamp_1 = Math.floor( dat/ 1000);
timestamp_2 = Math.floor(Date.now() / 1000); //this one is suppose to produce a correct timestamp
var addTimeStampMilisecs = 0;
if (timestamp_2 > timestamp_1)
{
addTimeStampMilisecs = timestamp_2-timestamp_1;
}
else if (timestamp_2 < timestamp_1)
{
addTimeStampMilisecs = timestamp_1-timestamp_2;
}
return addTimeStampMilisecs;
}
//writing a timestamp to the database
var destinationDateTimeStr = document.getElementById("dateyear").value+"-"+document.getElementById("datemonth").value+"-"+document.getElementById("dateday").value+"T"+document.getElementById("datehour").value+":"+document.getElementById("dateminute").value+":00";
var date2 = new Date(destinationDateTimeStr);
var eventDateTS = Math.floor(date2 / 1000); //convert to timestamp (with incorrect timezone)
eventDateTS += getTimestampMilisecondsGap(); //add (or decrese) the number of miliseconds from the timestamp because this function that generates the tmestamp returns a wrong number (the hour in the converted date is wrong)
//write the correct eventDateTS to your DB here...
Here's the scenario, I have a time that counts the time_taken by a user. What I want is to get the exact time_taken based from the timer. For example, a user take an exam, then after he/she take the exam, the time_taken will be submitted (e.g. 1hr 25mins 23secs). Please see my code below.
$(document).ready(function(){
var d;
setInterval(function(){
d = new Date();
dates = d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
$('#timeTaken').val(dates);
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="timeTaken" value="">
Here is Fiddle for the solution
https://jsfiddle.net/djzsddz6/1/
Ans Solution is below:
$(document).ready(function(){
var seconds = 0, minutes = 0 , hours = 0;
setInterval(function(){
seconds++;
if(seconds == 60){
minutes++
seconds = 0;
}
if(minutes == 60){
hours++
minutes = 0;
}
console.log(hours, minutes, seconds);
$('#timeTaken').val(`${hours}:${minutes}:${seconds}`);
}, 1000);
});
I don't really see the point to use an input there, you can just display in a span and when the form gets submitted take the time elapsed and send it with other data. Anyways, this should work for you:
$(document).ready(function () {
var time_start = new Date();
setInterval(function () {
var time_end = new Date();
var time_diff = (time_end - time_start);
// hours
var hours = Math.floor(time_diff / 1000 / 60 / 60);
// minutes
time_diff = time_diff - hours * 1000 * 60 * 60;
var minutes = Math.floor(time_diff / 1000 / 60);
// seconds
time_diff = time_diff - minutes * 1000 * 60;
var seconds = Math.floor(time_diff / 1000);
renderTime(hours, minutes, seconds);
}, 1000);
});
function renderTime (hrs, min, sec) {
var str = convertTime(hrs) + ":" + convertTime(min) + ":" + convertTime(sec);
$("#timeTaken").val(str);
}
function convertTime (val) {
return val < 10 ? "0" + val : val;
}
What's going on here is we have the time_start which does not change and we have setInterval function that is triggered every second. There we create new Date object, and the subtract the static one from it, which returns the time difference in milliseconds. We do the weird Math.flooring and subtracting, so we can have hours, minutes and seconds as an integers (not floats). Then we use render function to display the time inside an desired element.
Why I think it's a better solution then the others are, is that if you want to handle the user's page refresh you just need to save one variable to cookie or something else and it will work regardless of the page refresh.
Handling the page refresh would look like (with cookie saved for 2 hrs):
function updateTimeCookie () {
var time_now = new Date()
var value = JSON.stringify(time_now);
var expires = time_now.setTime(time_now.getTime() + 7200);
$.cookie("timeStart", value, { expires: expires });
};
// to get Date object from cookie: new Date(JSON.parse($.cookie("timeStart")))
To use $.cookie() you must first include jQuery Cookie Plugin.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
Working fiddle without cookie: https://jsfiddle.net/qc3axmf4/1/
Working fiddle with cookie: https://jsfiddle.net/ta8bnzs0/2/
Rather than getting date at every second you can keep the counter in set interval which will updated at every second. At the time of submission you can perform division and modulus operation to get exact time taken
Example
$(document).ready(function(){
var timer =0;
setInterval(function(){
Timer +=1;
// Code for display in hr mm and ss
$('#timeTaken').val(dates);
}, 1000'
});
You can also convert second in time valueby using moment.js
Hope this helps you.
Happy coding
i want to fire an event on specific date and time in javascript. for example ,
if current date and time is 19-11-2015 10:00 AM , and i set a timer on 19-11-2015 10:30 AM then , it should fire after 30 minutes. here set timer date could be after two days also.
my current code is as follows.
setTimer :function(hr , min){
var d1 = new Date();
var d2 = new Date();
console.log("Time 1 "+d1.getTime());
d2.setMinutes(d1.getMinutes() + min);
d2.setHours(d1.getHours() + hr);
console.log("Time 2 "+d2.getTime());
setTimeout(function(){
alert("called");
},d2.getTime());
alert("Before " + d1.getDate() + " - "+d1.getMonth() + " - "+d1.getFullYear() + "<>"+d1.getHours()+ ":"+d1.getMinutes()
+ "\n" +
"After " + d2.getDate() + " - "+d2.getMonth() + " - "+d2.getFullYear() + "<>"+d2.getHours()+ ":"+d2.getMinutes() );
},
i called it using setTimer(0,1); to fire a timer after one minute but its not getting fired.
Find out the time remaining using Date function and then pass it on to setTimeout function.No need to keep on checking the time.
$(document).ready(function(){
var d = new Date("November 19, 2015 17:00:00");
var d1 = new Date();
var timelimit = (d.getTime() - d1.getTime());
if(timelimit > 0) {
setTimeout(function(){
console.log(12345);
},timelimit);
}
});
Using setTimeout is not a reliable way to create timers.
You're much better off using setInterval and checking whether you've reached the correct time yet.
function setTimer(hours, minutes) {
var now = Date.now();
// work out the event time in ms
var hoursInMs = hours * 60 * 60 * 1000,
minutesInMs = minutes * 60 * 1000;
var triggerTime = now + hoursInMs + minutesInMs;
var interval = setInterval(function() {
var now = Date.now();
if(now >= triggerTime) {
alert('timer!');
// clear the interval to avoid memory leaks
clearInterval(interval);
}
}, 0);
}
You'll save yourself a lot of bother if you use Date.now which returns the date as the number of milliseconds since the epoch. Then you can just treat the problem numerically, rather than messing with the date api.
I am working on a project that requires a time in the future to be set using the Date object.
For example:
futureTime = new Date();
futureTime.setHours(futureTime.getHours()+2);
My questions is; once the future date is set, how can I round to the closest full hour and then set the futureTime var with it?
For example:
Given 8:55 => var futureTime = 9:00
Given 16:23 => var futureTime = 16:00
Any help would be appreciated!
Round the minutes and then clear the minutes:
var date = new Date(2011,1,1,4,55); // 4:55
roundMinutes(date); // 5:00
function roundMinutes(date) {
date.setHours(date.getHours() + Math.round(date.getMinutes()/60));
date.setMinutes(0, 0, 0); // Resets also seconds and milliseconds
return date;
}
The other answers ignore seconds and milliseconds components of the date.
The accepted answer has been updated to handle milliseconds, but it still does not handle daylight savings time properly.
I would do something like this:
function roundToHour(date) {
p = 60 * 60 * 1000; // milliseconds in an hour
return new Date(Math.round(date.getTime() / p ) * p);
}
var date = new Date(2011,1,1,4,55); // 4:55
roundToHour(date); // 5:00
date = new Date(2011,1,1,4,25); // 4:25
roundToHour(date); // 4:00
A slightly simpler way :
var d = new Date();
d.setMinutes (d.getMinutes() + 30);
d.setMinutes (0);
Another solution, which is no where near as graceful as IAbstractDownvoteFactory's
var d = new Date();
if(d.getMinutes() >= 30) {
d.setHours(d.getHours() + 1);
}
d.setMinutes(0);
Or you could mix the two for optimal size.
http://jsfiddle.net/HkEZ7/
function roundMinutes(date) {
return date.getMinutes() >= 30 ? date.getHours() + 1 : date.getHours();
}
As a matter of fact Javascript does this default which gives wrong time.
let dateutc="2022-02-17T07:20:00.000Z";
let bd = new Date(dateutc);
console.log(bd.getHours()); // gives me 8!!!!!
it is even wrong for my local time because I am GMT+2 so it should say 9.
moment.js also does it wrong so you need to be VERY carefull
Pass any cycle you want in milliseconds to get next cycle example 1 hours
function calculateNextCycle(interval) {
const timeStampCurrentOrOldDate = Date.now();
const timeStampStartOfDay = new Date().setHours(0, 0, 0, 0);
const timeDiff = timeStampCurrentOrOldDate - timeStampStartOfDay;
const mod = Math.ceil(timeDiff / interval);
return new Date(timeStampStartOfDay + (mod * interval));
}
console.log(calculateNextCycle(1 * 60 * 60 * 1000)); // 1 hours in milliseconds