I'm fairly new to JS and making a program that's supposed to count the number of days in between the given date and current date. Then it's supposed to calculate the number of years, months and remaining days between them from the calculated days. It's off by a couple of days for bigger dates. Any help would be greatly appreciated.
I've been trying it on dates such as 23.01.2076 and 23.01.1940 and changing the year and month one up or one down. For most of them it's off by 1-3 days.
HTML:
<html>
<head>
<meta charset="utf-8">
<script src="main.js"></script>
</head>
<body>
<div>
<input type="number" id="day" autocomplete="off">
<select id="month">
<option>January</option>
<option>February</option>
<option>March</option>
<option>April</option>
<option>May</option>
<option>June</option>
<option>July</option>
<option>August</option>
<option>September</option>
<option>October</option>
<option>November</option>
<option>December</option>
</select>
<input type="number" id="year" autocomplete="off">
</div>
<input type="button" id="date-button" value="Count">
<div id="result" >
</div>
</body>
</html>
Javascript:
let gram_start, difference;
const one_day = 24*60*60*1000;
let months_list = {
"January": [1,31],
"February": [2,28],
"March": [3,31],
"April": [4,30],
"May": [5,31],
"June": [6,30],
"July": [7,31],
"August": [8,31],
"September": [9,30],
"October": [10,31],
"November": [11,30],
"December": [12,31]
};
let month_index = Object.keys(months_list);
function leapyear(year) {
return (year % 100 === 0 ? year % 400 === 0 : year % 4 === 0);
}
window.onload = function count() {
document.getElementById("date-button").addEventListener("click", () => {
let years_write = 0;
let months_write = 0;
let day = parseInt(document.getElementById("day").value);
let month = document.getElementById("month").value;
let year = parseInt(document.getElementById("year").value);
let month_obj = months_list[month];
let target_date = new Date(year, month_obj[0]-1, day);
let today_date = new Date();
let matcher = new Date(today_date.getFullYear(),today_date.getMonth(), today_date.getDate());
//this works fine
if(target_date > today_date) {
gram_start = "There are that many days left to this date: <br>";
difference = Math.ceil((target_date - today_date) / one_day);
}
else if(target_date < today_date) {
gram_start = "There has been that many days since that date: <br>";
difference = Math.round((today_date - target_date) / one_day);
}
if(target_date < matcher)
difference--;
let remaining_days = difference;
if(target_date > today_date) {
while(remaining_days >= (leapyear(year) ? 366 : 365)) {
remaining_days -= leapyear(year) ? 366 : 365;
years_write++;
year--;
}}
else if(target_date < today_date) {
while(remaining_days >= (leapyear(year) ? 366 : 365)) {
remaining_days -= leapyear(year) ? 366 : 365;
years_write++;
year++;
}}
if(leapyear(year))
months_list.Luty[1] = 29;
else
months_list.Luty[1] = 28;
let i = month_obj[0]-1;
if(target_date > today_date) {
while(remaining_days >= (months_list[month_index[i]][1])) {
remaining_days -= (months_list[month_index[i]][1]);
months_write++;
i--;
}}
else if(target_date < today_date) {
while(remaining_days >= months_list[month_index[i]][1]) {
remaining_days -= months_list[month_index[i]][1];
months_write++;
i++;
}}
document.getElementById("result").innerHTML = gram_start + difference + " days, so:" + years_write + " years, " + months_write + " months and " + remaining_days + " days.";
})};
Related
I am in need of having a3 checkboxes that should have a tick mark from 2 pm till 11 pm IST in javascript or HTML. This is what I tried
<html>
<body>
<center>
<span style="margin-left:50px; margin-top:0px;">
<p align="left"><font color="white"> <b> India Time: 2pm to 11pm IST </b>
</br>
<input type="checkbox" id="user1" name="user1" value="user1" > User1<br>
<input type="checkbox" id="user2" name="user2" value="user2" > User2<br>
<input type="checkbox" id="user3" name="user3" value="user3" > User3<br>
</p>
<img border="1" src="https://i.postimg.cc/VkPzvHCJ/gh.png" style=" margin-top:-129px;" >
</span>
<h3 style= "font-family: "Gotham A","Gotham B",sans-serif;>
<br> <p align="center" style=" margin-top:-30px;"> <font color="#339933"> <b>RStudio Dashboard
</h3></P>
</body>
<script>
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd}
if(mm<10){mm='0'+mm}
var today = dd+'/'+mm+'/'+yyyy;
var holidays = [];
holidays = ["01/01/2019" , "26/01/2019" , "20/02/2019" , "01/05/2019" , "27/05/2019" , "04/06/2019", "04/07/2019" , "15/08/2019" , "02/09/2019" , "10/09/2019" , "02/10/2019" , "28/11/2019" , "25/12/2019"];
//var n = str.indexOf("welcome");
if {
var startTime = '2:00 PM';
var endTime = '11:00 PM';
var curr_time = getval();
//var curr_time = '12:39 AM';
//alert(curr_time);
if (get24Hr(curr_time) > get24Hr(startTime) && get24Hr(curr_time) < get24Hr(endTime)) {
//in between these two times
//alert("Yes")
document.getElementById("sid").checked = true;
document.getElementById("anil").checked = true;
document.getElementById("vin").checked = true;
} else {
//document.getElementById("user1").checked = true;
//document.getElementById("user2").checked = true;
}
function get24Hr(time){
var hours = Number(time.match(/^(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if(AMPM == "PM" && hours<12) hours = hours+12;
if(AMPM == "AM" && hours==12) hours = hours-12;
var minutes = Number(time.match(/:(\d+)/)[1]);
hours = hours*100+minutes;
console.log(time +" - "+hours);
return hours;
}
function getval() {
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10) minutes = "0" + minutes;
var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}
var current_time = hours + ":" + minutes + " " + suffix;
return current_time;
}
}
else
{
print ("hello")
}
</script>
</html>
This is what I tried. The code is working, but it seems a bit complicated. Is there any simple method?
The only requirement is to tick the checkboxes from 2 pm to 11 pm IST
Add this js function. And then add "onClick" on every Input. Also the name must be the same.
<script language="JavaScript">
function toggle(source) {
checkboxes = document.getElementsByName('user');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}
</script>
<input type="checkbox" onClick="toggle(this)" id="user1" name="user" value="user1" > User1<br>
<input type="checkbox" onClick="toggle(this)" id="user2" name="user" value="user2" > User2<br>
<input type="checkbox" onClick="toggle(this)" id="user3" name="user" value="user3" > User3<br>
I want to write code for a counter which countdown from 4 hours in hour, minute and second components (3:59:59 ... 3:59:58 ..... 0:0:1 ... 0:0:0) in which the user can increment or decrement any of those components by using +/-icons. I wrote a code but I cannot make it? How can I complete it? In my code just increase/decrease icon works.
function increment() {
hour = parseInt(document.getElementsByName("hour")[0].value);
minute = parseInt(document.getElementsByName("minute")[0].value);
second = parseInt(document.getElementsByName("second")[0].value);
if (second + 1 == 61) {
minute = minute + 1;
if (minute == 61) {
hour = hour + 1;
if (hour == 3) {
hour = 0;
}
minute = 0;
}
second = 0;
} else {
second += 1;
}
document.getElementsByName("hour")[0].value = hour.toString();
document.getElementsByName("minute")[0].value = minute.toString();
document.getElementsByName("second")[0].value = second.toString();
}
function decrement() {
hour = parseInt(document.getElementsByName("hour")[0].value);
minute = parseInt(document.getElementsByName("minute")[0].value);
second = parseInt(document.getElementsByName("second")[0].value);
if (second - 1 <= 0) {
minute -= 1;
if (minute <= 0) {
hour -= 1;
if (hour <= 0) {
hour = 2;
minute = 60;
} else {
minute = 60;
}
}
second = 60;
} else {
second -= 1;
}
document.getElementsByName("hour")[0].value = hour.toString();
document.getElementsByName("minute")[0].value = minute.toString();
document.getElementsByName("second")[0].value = second.toString();
}
<html>
<body>
<table>
<tr>
<td>Hour</td>
<td>
<input type="text" name = "hour" placeholder = "HOUR" value="0"/>
</td>
<td>Minute</td>
<td>
<input type="text" name="minute" placeholder="MINUTE" value="0"/>
</td>
<td>Second</td>
<td>
<input type="text" name="second" placeholder="SECOND" value="0"/>
</td>
</tr>
<tr>
<td><br>
<input type="button" name="+" value="+" onclick= "return increment()"/>
</td>
<td><br>
<input type="button" name="-" value="-" onclick="return decrement()"/>
</td>
</tr>
</table>
</body>
</html>
Here is how i would go about it, first of all, you had the script execute before the body which caused problems since the elements you were trying to select didn't exist yet,
also, you're trying to do everything everywhere, but if you keep state, it is much more manageable
<script>
const maxTime = 4 * 60 * 60; // 4 hours in seconds
const hours = document.querySelector("[name='hour']");
const minutes = document.querySelector("[name='minute']");
const seconds = document.querySelector("[name='second']");
let remaining = maxTime;
let counter = setInterval(decrement, 1000);
function increment() {
remaining = Math.max(maxTime, remaining + 1);
display();
}
function decrement() {
remaining = Math.max(0, remaining - 1);
display();
}
function display() {
const time = new Date(remaining * 1000).toISOString();
hours.value = time.slice(11, 13);
minutes.value = time.slice(14, 16);
seconds.value = time.slice(17, 19);
}
</script>
You can use the setInterval function
This will call your decrement function every second
setInterval(decrement, 1000)
The first parameter is the function to be executed.
The second parameter indicates the number of milliseconds before execution.
I have poured over this code and I feel pretty positive about it. That being said, something is obviously missing, as the program itself comes up with an empty clock when run in the browser. I know that the brackets and parentheses all have a matching set, and I am fairly confident in my functions. The chrome developer tools were unhelpful. Anyone with a good eye for Javascript able to see what is missing here?
"use strict";
var $ = function(id) {
return document.getElementById(id);
};
var displayCurrentTime = function() {
var today = new Date();
var hour = today.getHours();
var min = today.getMinutes();
var sec today.getSeconds();
var ap = "AM";
if (hour > 12) {
h = h - 12;
ap = "PM";
} else {
switch (hour) {
case 12:
ap = "PM";
break;
case 0:
ap = "AM";
break;
}
}
$("hours").firstChild.nodeValue = padSingleDigit(hours);
$("minutes").firstChild.nodeValue = padSingleDigit(min);
$("seconds").firstChild.nodeValue = padSingleDigit(sec);
$("ap").firstChild.nodeValue = padSingleDigit(ap);
};
var padSingleDigit = function(num) {
if (num < 10) {
return "0" + num;
} else {
return num;
}
};
window.onload = function() {
displayCurrentTime();
setInterval(displayCurrentTime, 1000);
};
<html>
<head>
<meta charset="UTF-8">
<title>Clock</title>
<link rel="stylesheet" href="clock.css">
<script src="clock.js"></script>
</head>
<body>
<main>
<h1>Digital clock</h1>
<fieldset>
<legend>Clock</legend>
<span id="hours"> </span>:
<span id="minutes"> </span>:
<span id="seconds"> </span>
<span id="ampm"> </span>
</fieldset>
</main>
</body>
</html>
You simply have a lot of (3) typos ...
"use strict";
var $ = function(id) {
return document.getElementById(id);
};
var displayCurrentTime = function() {
var today = new Date();
var hour = today.getHours();
var min = today.getMinutes();
var sec = today.getSeconds();
var ap = "AM";
if (hour > 12) {
hour = hour - 12;
ap = "PM";
} else {
switch (hour) {
case 12:
ap = "PM";
break;
case 0:
ap = "AM";
break;
}
}
$("hours").firstChild.nodeValue = padSingleDigit(hour);
$("minutes").firstChild.nodeValue = padSingleDigit(min);
$("seconds").firstChild.nodeValue = padSingleDigit(sec);
$("ampm").firstChild.nodeValue = padSingleDigit(ap);
};
var padSingleDigit = function(num) {
if (num < 10) {
return "0" + num;
} else {
return num;
}
};
window.onload = function() {
displayCurrentTime();
setInterval(displayCurrentTime, 1000);
};
<main>
<h1>Digital clock</h1>
<fieldset>
<legend>Clock</legend>
<span id="hours"> </span>:
<span id="minutes"> </span>:
<span id="seconds"> </span>
<span id="ampm"> </span>
</fieldset>
</main>
*there are other (non-functional) problems in this code, but since it is not the Q, I'd not change them to keep this answer on point.
I'm using Contact Form 7 as a booking tool for a restaurant. The date you can book a table is set on next day by default. Also booking for the present day is not possible.
I want the tool to show the present date until 2pm and after 2pm it automatically switches to the next day's date. Also it makes booking for the present day unpossible after 2pm.
I'm a complete newbie in coding, I hope you guys can help me out.
This is how the Contact Form is currently set up:
<label> Personenanzahl *
[select* res-number "1 Person" "2 Personen" "3 Personen" "4 Personen" "5 Personen" "6 Personen"] </label>
<label> Datum *
[date* res-date id:datepicker min:today] </label>
<div class="vc_col-sm-6 padding-column"><label> Start *
[select* res-start id:start-time "17:00" "17:15" "17:30" "17:45" "18:00" "18:15" "18:30" "18:45"
"19:00" "19:15" "19:30" "19:45" "20:00" "20:15" "20:30" "20:45" "21:00" "21:15" "21:30" "21:45"
"22:00" "22:15" "22:30" "22:45" "23:00" "23:15" "23:30" "23:45" "00:00" "00:15" "00:30" "00:45"
"01:00"] </label></div>
<div class="vc_col-sm-6 padding-column"><label> Ende *
[select* res-end id:end-time "17:00" "17:15" "17:30" "17:45" "18:00" "18:15" "18:30" "18:45"
"19:00" "19:15" "19:30" "19:45" "20:00" "20:15" "20:30" "20:45" "21:00" "21:15" "21:30" "21:45"
"22:00" "22:15" "22:30" "22:45" "23:00" "23:15" "23:30" "23:45" "00:00" "00:15" "00:30" "00:45"
"01:00"] </label></div>
<label> Name *
[text* res-name] </label>
<label> Telefon *
[tel* res-tel] </label>
<label> E-Mail Adresse *
[email* res-email] </label>
[submit "Senden"]
And this is additional code which is implemented on the website:
<script type="text/javascript">
// initialize datepicker
var datepicker = jQuery('#datepicker');
var today = new Date();
var tomorrow = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
var dd = today.getDate();
var mm = today.getMonth()+1; // January is 0!
var yyyy = today.getFullYear();
var tomday = tomorrow.getDate();
var tommonth = tomorrow.getMonth() + 1;
var tomyear = tomorrow.getFullYear();
if(tomday<10){tomday='0'+tomday} if(tommonth<10){tommonth='0'+tommonth} tomorrow = tomyear+'-'+tommonth+'-'+tomday;
jQuery(datepicker).attr('value', tomorrow);
// initialize time boxes
var startTimeBox = jQuery('#start-time')[0];
var endTimeBox = jQuery('#end-time')[0];
jQuery(startTimeBox).val("17:00");
jQuery(endTimeBox).val("18:45");
// handling of time changes
jQuery(startTimeBox).change(function (event) {
var startTimeValue = event.currentTarget.value;
var startHour = Number(startTimeValue.slice(0,2));
var startMinute = Number(startTimeValue.slice(3,5));
var endHour = 0;
var endMinute = 0;
if ((startHour == 23) || (startHour == 0) || (startHour == 1)) {
if ((startHour == 23) && (startMinute == 0)) {
endHour = 0;
endMinute = 45;
} else {
endHour = 1;
endMinute == 0;
}
} else {
if (startMinute == 0) {
endHour = startHour + 1;
endMinute = 45;
} else if (startMinute == 15) {
endHour = startHour + 2;
endMinute = 0;
} else if (startMinute == 30) {
endHour = startHour + 2;
endMinute = 15;
} else if (startMinute == 45) {
endHour = startHour + 2;
endMinute = 30;
}
if (endHour == 24) {
endHour = 0;
}
}
if (endHour == 24) {
endHour = 0;
}
var endHourString = endHour.toString();
var endMinuteString = endMinute.toString();
if (endHourString.length == 1) {
endHourString = "0" + endHourString;
}
if (endMinuteString.length == 1) {
endMinuteString = "0" + endMinuteString;
}
var endTimeString = endHourString + ":" + endMinuteString;
jQuery(endTimeBox).val(endTimeString);
});
</script>
Thank you very much!
You can use contact form7 date picker plugin its easy and usefull for time and date with curent tim
actual output and expected outputs are mentioned in snapshots :[Snapshot of case 1][1][Snap Shot of Case2 ][2].
I get errors while calculating time difference between start-time and end-time. The errors:
If start-time is greater than end-time then calculation is wrong.
If weekends is included and start-time is greater than end-time.
Please suggest how to resolve the errors in my code.
// Wire up Date and DateTime pickers (with default values)
$("#start").datetimepicker();
$("#end").datetimepicker();
$("#workday_start").timepicker({
hour: 8
}).val("8:00");
$("#workday_end").timepicker({
hour: 17
}).val("17:00");
// Calculate the number of hours worked
$("#calculate").click(function() {
// Are all fields complete?
var allFieldsComplete = $('.data input').filter(function() {
return $(this).val().toString().length == 0;
}).length == 0;
// Ensure all fields are present
if (allFieldsComplete) {
// Capturing the input dates
var startDate = moment($("#start").val());
var endDate = moment($("#end").val());
var daysDiff = endDate.diff(startDate, 'days');
// Capturing the input times
var startTime = startDate.hours();
var endTime = endDate.hours();
var timeDiff;
var operational_hr_start = new Date("1/1/0001 " + $("#workday_start").val()).getHours() + (new Date("1/1/0001 " + $("#workday_start").val()).getMinutes() / 60)
var operational_hr_end = new Date("1/1/0001 " + $("#workday_end").val()).getHours() + (new Date("1/1/0001 " + $("#workday_end").val()).getMinutes() / 60);
var includeWeekends = $('input[type=checkbox]').prop('checked');
if (startTime < operational_hr_start) {
startTime = operational_hr_start;
}
if (endTime > operational_hr_end) {
endTime = operational_hr_end;
}
timeDiff = endTime - startTime;
if (daysDiff > 0) {
var response= workingHoursBetweenDates(startDate, endDate, operational_hr_start, operational_hr_end, includeWeekends);
$("#result").val(response);
} else if (daysDiff === 0) {
var dayNo = startDate.day();
if (dayNo === 0 || dayNo === 6) {
alert('Weekend!!!');
return;
} else {
if (timeDiff > 0) {
alert('Total hours worked: ' + timeDiff);
} else {
alert('End time must be greater than start time!!!');
}
}
} else {
alert('End date must be greater than start date!!!');
}
} else {
// One or more of the fields is undefined or empty
alert("Please ensure all fields are completed.");
}
});
});
// Simple function that accepts two parameters and calculates the number of hours worked within that range
function workingHoursBetweenDates(startDate, endDate, operationalHourStart, operationalHourEnd, includeWeekends) {
var incrementedDate = startDate;
var daysDiff = endDate.diff(startDate, 'days');
var workingHrsPerDay = operationalHourEnd - operationalHourStart;
var startHrs = startDate.hours(),
endHrs = endDate.hours(),
totalHoursWorked = 0;
if (startDate.hours() < operationalHourStart) {
startHrs = operationalHourStart;
}
if (endDate.hours() > operationalHourEnd) {
endHrs = operationalHourEnd;
}
/*
* The below block is to calculate the duration for the first day
*
*/
{
totalHoursWorked = operationalHourEnd - startHrs;
if (startDate.day() === 0 || startDate.day() === 6) {
totalHoursWorked = 0;
if (includeWeekends) {
totalHoursWorked = operationalHourEnd - startHrs;
}
}
incrementedDate = incrementedDate.add(1, 'day');
}
/*
* The below if block is to calculate the duration for the last day
*
*/
{
var lastDayWorkHrs = endHrs - operationalHourStart;
totalHoursWorked = totalHoursWorked + lastDayWorkHrs;
if (endDate.day() === 0 || endDate.day() === 6) {
if (includeWeekends) {
totalHoursWorked = totalHoursWorked + lastDayWorkHrs;
} else {
totalHoursWorked = totalHoursWorked - lastDayWorkHrs;
}
}
}
// The below for block calculates the total no. of hours excluding weekends. Excluding first and last day
for (var i = 1; i < daysDiff; i++) {
/*
* Weekname mapping. There are default week
* numbers (i.e., 0 to 6. 0 means Sunday, 1 means Monday, ... 6 means Saturday)
* which are returned by moment library.
*
*/
if (incrementedDate.day() === 0 || incrementedDate.day() === 6) {
// Do nothing
if (includeWeekends) {
totalHoursWorked = totalHoursWorked + workingHrsPerDay;
}
} else {
totalHoursWorked = totalHoursWorked + workingHrsPerDay;
}
incrementedDate = incrementedDate.add(1, 'day');
}
return totalHoursWorked;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-ui-timepicker-addon/1.6.3/jquery-ui-timepicker-addon.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-ui-timepicker-addon/1.6.3/jquery-ui-timepicker-addon.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet"/>
<pre>Variables</pre>
<table>
<tr>
<th>START</th>
<th>END</th>
<th>WORKDAY START</th>
<th>WORKDAY END</th>
<th>Result</th>
<th>INCLUDE WEEKENDS?</th>
</tr>
<tr class='data'>
<th><input id='start' /></th>
<th><input id='end' /></th>
<th><input id='workday_start' /></th>
<th><input id='workday_end' /></th>
<th><input id='result' value=" "/></th>
<th><input id='include_weekends' type='checkbox' /></th>
</tr>
</table>
<hr />
<input id='calculate' type='button' value='Calculate Hours Worked' />