Troubles with getDay in Javascript - javascript

Hi this seems simple enough but it's not working! I am trying to take two Epoch numbers and calculate the day of the week in a loop for that current day. I need this because I want to not count the days that are on the weekend (i.e. 0 or 6).
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display todays day of the week.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var oneDay = 86400;
var days = 0;
var currDay = 0;
//var d = new Date();
// get the start time in Epoch
var dayTime = 1425531600 //from the user selection
var endTime = 1425960000
//while our dayTime is less than the end time,
//loop through the days and count them.
while (dayTime < endTime) {
// advance one day
dayTime = dayTime + oneDay;
document.write("out:"+dayTime+"<br>")
//turn the new time in Epoch into a date
var d = new Date(dayTime);
document.write("out:"+d.getDay()+"<br>")
}
}
</script>
</body>
</html>
The output looks like this:
out:1425618000
out:6
out:1425704400
out:6
out:1425790800
out:6
out:1425877200
out:6
out:1425963600
out:6
Why am I ALWAYS getting '6' for each Epoch? Something wrong with my Epoch values? Note, it's 5 days so each day is 86400 long.
I copied the code into this page to test it:
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_getday

In new Date(x), x needs to be in unixEpoch format (milliseconds) - or other formats. To solve your problem, just multiply all your values by 1000:
window.onload = function() {
var oneDay = 86400000;
var days = 0;
var currDay = 0;
//var d = new Date();
// get the start time in Epoch
var dayTime = 1425531600000 //from the user selection
var endTime = 1425960000000
//while our dayTime is less than the end time,
//loop through the days and count them.
while (dayTime < endTime) {
// advance one day
dayTime = dayTime + oneDay;
document.body.insertAdjacentHTML('beforeend',"out:" + dayTime + "<br>")
//turn the new time in Epoch into a date
var d = new Date(dayTime);
document.body.insertAdjacentHTML('beforeend',"out:" + d.getDay() + "<br>")
}
}

Related

How to find difference of two times using moment?

These are my time formats;
const startTime = "20:00";
const endTime = "05:00";
const startDate = "2021-01-20T00:00:00+05:30"
const days = "1"; // it can be 0 also
Now, I need to find the difference between startTime and endTime using moment, and as the "days = 1", it means the endTime ends on the next day:
So the expected output would be,
9hrs 0mints on 2021-01-21
( As the days says 1, we need to count one day and show the endDate and if days=0 means same date as start date )
How to perform this using moment?
As tried I,
var dif = moment.duration(endTime.diff(startTime))
But it gives the error "endTime.diff is not a function". Please help.
You can use this way when the time duration of more than 24 hours.
var startTime = moment("20:23", "HH:mm");
var endTime = moment("05:10", "HH:mm");
var days ="1";
// calculate the days in milliseconds
var duration = moment.duration(parseInt(days), 'days');
var day = duration.asMilliseconds();
//calculate the total milliseconds
var ms = day + moment(endTime,"HH:mm").diff(moment(startTime,"HH:mm"));
var d = moment.duration(ms);
//get the total duration
var s = Math.floor(d.asHours())+" hrs " + moment.utc(ms).format("mm") + " mins";
console.log(s);

Date and Time Difference and Average time

I have two times (basically start time and end time). Also, I have the number of questions played by the user. I wanna know the average time user spent for each question.
//startGameTime: 2019-07-27T07:58:42.000Z
//endGameTime: 2019-07-27T07:59:57.000Z
function averageQuestionTime(startGameTime, endGameTime, totalNumberOfQuestions) {
var d1 = new Date(startGameTime);
var d2 = new Date(endGameTime);
var d1msecs = new Date(d1).getTime(); // get milliseconds
var d2msecs = new Date(d2).getTime(); // get milliseconds
var avgTime = (d1msecs + d2msecs) / totalNumberOfQuestions;
var date = new Date(avgTime);
var hour = date.getUTCHours();
var min = date.getUTCMinutes();
var sec = date.getUTCSeconds();
var day = date.getUTCDate() - 1;
return (day + ":" + hour + ":" + min + ":" + sec)
}
I understand my logic is completely flawed as the units for date and time and nos of questions are different. What is the best way to achieve the result ?
There are good libraries which prevent the users from having to reinvent the wheel every time they want to manipulate date/time in Node.
Obtaining time difference is pretty simple (I can see you are doing it correctly to obtain the difference in milliseconds) and libraries make them even simpler.
See how simple it is using momentJS
var moment = require('moment');
var startDate = moment('2019-7-24 00:00:00', 'YYYY-M-DD HH:mm:ss');
var endDate = moment('2019-7-24 05:27:31', 'YYYY-M-DD HH:mm:ss');
var diffSeconds = endDate.diff(startDate, 'seconds');
var diffHours endDate.diff(startDate, 'seconds');
console.log(`Avg in secs: ${diffSeconds / totalNumberOfQuestions}`);
console.log(`Avg in secs: ${diffHours/ totalNumberOfQuestions}`);

jquery - assigning values to an input not working

I have three input controls in a form as,
date (which display the current date but user can select any date from a calendar)
start time(current time)
end time(start time + 30 minutes)
on page load
HTML:
Date:<input type="text" name="txtdate" id="txtdate" />
Start time:<input type="time" name="txtstart" id="txtstart" />
End time:<input type="time" name="txtend" id="txtend" />
I use jquery to get this done and the code is as follows
jquery:
$(document).ready(function() {
$("#txtdate").datepick({dateFormat:'yyyy-mm-dd',minDate: 0});
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
var year1 = d.getFullYear();
var hour = d.getHours();
var mins = d.getMinutes();
var today = year1 + '/' + month + '/' + day;
$("#txtdate").val(today);
var time = hour + ":" + mins;
$("#txtstart").val(time);
var a = time.split(':');
var totmins = (+a[0])* 60 + (+a[1])+30;
var nhour = Math.floor(totmins/60);
var nmins = totmins%60;
var ntime = nhour + ":" + nmins;
$("#txtend").val(ntime);
});
in the above code it displays the current date, time and adds up 30 minutes to the current time correctly but sometimes when assigning values, the start time and end time fields don't display the time! for an example,
when current time is 12.00 AM, no value is displayed in start time and end time input fields
I don't see any error in the code but since i'm new to jquery i need to know if i had done anything wrong here (may be when assigning values) or is there another way to do this?
Note:
It should be noted that I have use HTML 5 input type time control to input start time and end time
My guess to your question is that after adding 30 minute to your Start Time, End Time is already the next day.
Take this for example.
Start Time: 23.50
Based on your calculation, +30min gives you
End Time: 24.20
24.20 is an invalid value for input[type='time']
Edit: Jacob's answer solves the problem to your flawed algorithm.
Edit 2: Modifying Jacob's answer, this will get you the endDate
var d = new Date(); //get current time.
var thirtyMinutes = 30*60*1000; //30 minutes in milliseconds
var futureDate = new Date(d.getTime() + thirtyMinutes); //current time in milliseconds + 30 minutes in milliseconds.
var endDateHour = futureDate.getHours();
var endDateMinutes = futureDate.getMinutes();
if (endDateMinutes<10) {
endDateMinutes = "0"+endDateMinutes;
}
var endDate = endDateHour + ':' + endDateMinutes;
Don't bother with this complicated "add 30 minutes" logic when you can simply use Date which is already good at date/time math.
var d = new Date();
// ...
var thirtyMinutes = 30*60*1000;
var futureDate = new Date(d.getTime() + thirtyMinutes);
var ntime = futureDate.getHours() + ':' + futureDate.getMinutes();

Javascript getDate() Method for a Countdown Timer

In Javascript whenever we call the getDate() method a value of 1-31 is returned for the particular day of the month. This creates a problem in my countdown timer when I specify a future date in var goal that is greater than 31 which causes the countdown timer to output '12' instead of the number of days that are actually left until the future date.
function twoDigits(number) {return (number < 10 ? '0' : '') + number};
var goal = "Sun January 01 2012 00:00:01";
goal = new Date(goal);
var now = new Date();
var count = new Date(goal.getTime() - now.getTime());
var day = count.getDate() -1;
var hour = count.getHours()-1;
var format = twoDigits(day) + ":" + twoDigits(hour) + ":" + twoDigits(count.getMinutes()) + ":" + twoDigits(count.getSeconds());
$(function () {
$('#counter').countdown({
image: 'digits.png',
startTime: format
});
});
Any ideas how I could fix this?
function padLeft(str,len,char) {
len=Number(len)||1;
char=String(char)||" ";
for(var i=0;i<len;i++)str=char+str;
return str.substr(str.length-len);
}
//$(document).ready(function() {
var goal = "Sun January 01 2011 00:00:01";
goal = new Date(goal);
var now = new Date();
var count = goal.getTime() - now.getTime();
var sign = count/Math.abs(count);
count = Math.abs(count);
var days = Math.floor(count/(24*60*60*1000));
count -= days*24*60*60*1000;
var hours = Math.floor(count/(60*60*1000));
count -= hours*60*60*1000;
var minutes = Math.floor(count/(60*1000));
count -= minutes*60*1000;
var secs = Math.floor(count/1000);
var startTime = days +":"+ padLeft(hours,2,"0") +":"+ padLeft(minutes,2,"0") +":"+ padLeft(secs,2,"0");
alert(startTime);
/*
$("#counter").countdown({
image: 'digits.png',
startTime: startTime,
format: "dd:hh:mm:ss"
});
*/
//}
This is not an exact fix for your code's issue
but if you want helper methods for dates, take a look at sugar.js it has a host of helper methods, like easily calculating the difference in days between now and a given date.
look at the features page for all date methods
you could use this function for example:
var goal = "Sun January 01 2011 00:00:01";
goal = new Date(goal);
var difference = goal.daysFromNow();
daysFromNow() is already an alias for daysUntil() & daysSince() which are for calculating differences in the past or future, daysFromNow() takes care of the past and future at once :)
and that variable would give you the total amount of days, even if it's more than 31 days.

I want to validate when date and time selected is past current date and time

I have two readonly textboxes, one textbox is linked with the jquery datepicker and the other textbox is linked with the timepicker jquery. Now the great thing about the jquery datepicker is that I can range my dates so that the user cannot select any dates before the current date. But the Jquery timepicker cannot be ranged so the time is before the current time.
Because of this there is a possbile chance that the user can select the current date but a time before the current time. Obviously this means the time chosen has passed the current time of the current day which I don't want happening. So a validation is needed where if date textbox and time textbox is past the current date and time, then a message is displayed stating "The Date and Time you have selected is before the Current Date and Time" else if time and date together is past current date and time then display "".
How can I do this. Below is my best attempt at it but I couldn't get it to work.
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Create a Session</title>
<script type="text/javascript">
function validation() {
var dateTextO = document.getElementById("datepicker");
var timeTextO = document.getElementById("timepicker");
var errDateTimeMsgO = document.getElementById("dateTimeAlert")
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10){
minutes = "0" + minutes
}
if (hours < 10){
hours = "0" + hours
}
if((dateTextO < currentDate) && (timeTextO < currentTime)){
errDateTimeMsgO.innerHTML = "The Date and Time you have selected is before the Current Date and Time";
} else {
errDateTimeMsgO.innerHTML = "";
}
}
</script>
</head>
<body>
<form action="create_session.php" method="post" name="sessionform">
<p><strong>4: Date:</strong> <input type="text" id="datepicker" readonly="readonly"></p>
<p><strong>5: Time:</strong> <input type="text" id="timepicker" readonly="readonly"><span class="timepicker_button_trigger"><img src="Images/clock.gif" alt="Decrease" /></span></p>
<div id="dateTimeAlert"></div>
</form>
</body>
actually the date generated by new Date() is something like this
Wed Jul 20 2011 19:09:46 GMT+0530 (IST)
but your datepicker time maybe something like this
28-07-2011
those are in two different formats . so you can not comapare , so you have to get those to one format
var checkindatestr = document.getElementById("datepicker");
var dateParts = checkindatestr.split("-");
var checkindate = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);
var now = new Date();
var difference = now - checkindate;
you can find difference of the 2 days this way .
i ll find a way and tell you how to compare 2 times......... :D
UPDATE
var checkindatestr = document.getElementById("datepicker");
var dateParts = checkindatestr.split("-");
var checkindate = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);
var nowdate = new Date();
var differenceDate = parseInt(nowdate) - parseInt(checkindate);
var checkintimestr = document.getElementById("timepicker");
var timeParts = checkindatestr.split(":");
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
if(( differenceDate >= 0) && (parseInt(hours) >= parseInt(timeParts[0])) && (parseInt(minutes) > parseInt(timeParts[1]) )){
errDateTimeMsgO.innerHTML = "The Date and Time you have selected is before the Current Date and Time";
} else {
errDateTimeMsgO.innerHTML = "";
}
}

Categories