Javascript days in October - javascript

I have a funny bug in my calculation about interest days. I go through each day and check which day it is (1 to 31). Now I found a problem: In October the count doesn't work properly. That means the 27th is the 26th, or the 29th is the 28th. Is this a well know problem?
Maybe the problem is in my code, but, because it works over another period, it seems to be fine.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function berecheZinstage() {
//eingabe von den Feldern holen
var strVon = txtVonDatum.value;
var strBis = txtBisDatum.value;
//label um das Resultat anzuzeigen
var resultatTage = document.getElementById("lblTage");
var resultatZinsTage = document.getElementById("lblZinstage");
//tag als Milisekunden
var tagMs = 86400000;
var monatCount;
//Eingabeformat umwandeln für die Berechung
strVon = strVon.replace(/-/g, "/");
strBis = strBis.replace(/-/g, "/");
var vonDatum = new Date(strVon);
var bisDatum = new Date(strBis);
var zinsTage = 0;
if (bisDatum > vonDatum) {
var totTage = bisDatum - vonDatum;
var nDays = Math.round(totTage / (1000 * 60 * 60 * 24));
var pruefMS = vonDatum.getTime();
var startMS = vonDatum.getTime();
var endeMS = bisDatum.getTime();
var febCount = 0;
var langCount = 0;
var tage = 0;
for (var i = 0; i < nDays; i++) {
pruefMS = pruefMS + tagMs;
var pruefDatum = new Date(pruefMS);
var pruefMonat = pruefDatum.getMonth();
var pruefJahr = pruefDatum.getFullYear();
var pruefTag = pruefDatum.getDate();
if (pruefTag == 1 && pruefDatum != startMS) {
if (pruefMonat == 2) {
var istSchaltjahr = new Date(pruefJahr, 1, 29).getMonth() == 1;
if (istSchaltjahr) {
tage++;
}
else {
tage = tage + 2;
}
}
}
if (pruefTag != 31) {
tage++;
}
}
resultatZinsTage.innerText = tage.toString();
resultatTage.innerText = pruefTag;//nDays.toString();
}
else {
resultatTage.innerText = "Bis Datum muss grösser sein als von Datum";
}
}
</script>
<title>Zinstage berechen</title>
</head>
<body>
<table style="width:100%;">
<tr>
<td style="width:100px;"><input id="txtVonDatum" type="text" /></td>
<td style="width:100px;"><input id="txtBisDatum" type="text" /></td>
<td style="width:100px;"><button id="btnCalcDays" type="button" onclick="berecheZinstage();">Berechnen</button></td>
<td> </td>
</tr>
<tr>
<td>Tage:</td>
<td><label id="lblTage"></label></td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>Zinstage:</td>
<td><label id="lblZinstage"></label></td>
<td> </td>
<td> </td>
</tr>
</table>
</body>
</html>
Thanks, Marlowe

I don't understand what this code is trying to achieve, but the problem is DST (Daylight Saving Time).
Adding 86400000 millis for each day should work ok. But in locales that use DST (default in Germany), the result of date "2013/10/01 00:00:00" + 31*86400000 would be "2013/10/31 23:00:00".
Actually if we include the timezone, it would be "2013/10/01 00:00:00 GMT+0200" + 31*86400000 would be "2013/10/31 23:00:00 GMT+0100", so the addition is correct in UTC terms.
Likewise in March, the resulting date would be "2013/04/01 01:00:00", but we don't see the error since we're only counting the days.
When performing operations like this, always use UTC to avoid headaches :)

Here is now the working code. With the hint given by foibs I've built a little hack to calculate the interest days.
<script type="text/javascript">
function calcInterestDays() {
//get the values from the input fields
var strFrom = document.getElementById("txtFromDate").value;
var strTill = document.getElementById("txtTillDate").value;
//format strings
strFrom = strFrom.replace(/-/g, "/");
strTill = strTill.replace(/-/g, "/");
var fromDate = new Date(strFrom);
var tillDate = new Date(strTill);
var msDay = 86400000;
var startMS = fromDate.getTime();
var totDays = Math.round((tillDate - fromDate) / (1000 * 60 * 60 * 24));
var totMs = startMS;
var outputStr = "";
var days = 0;
for (var i = 0; i < totDays; i++) {
totMs = totMs + msDay;
var checkDate = new Date(totMs);
var splitDate = checkDate.toString().split(" ");
if (splitDate[6] == "0200") {
var calcDay = new Date(totMs);
}
else {
var calcDay = new Date(totMs + 3600000);
}
if (calcDay.getDate() == 1 && totMs != startMS) {
if (calcDay.getMonth() == 2) {
var istSchaltjahr = new Date(calcDay.getFullYear(), 1, 29).getMonth() == 1;
if (istSchaltjahr) {
days++;
}
else {
days = days + 2;
}
}
}
if (calcDay.getDate() != 31) {
days++;
}
outputStr = outputStr + "<br>" + calcDay;
}
document.getElementById("lblTotDays").innerHTML = totDays;
document.getElementById("lblInterestDays").innerHTML = days;
document.getElementById("output").innerHTML = outputStr;
}
</script>
Thanks for all the help.

Related

return to zero after reach max value and add the remaining value javascript

sorry i am newbie here
i need some help,
this case like notice a time.
when real time passes input value, then span with id alertLabel will change.
the problem is, if input value plus with input with id Duration will exceed real minutes or hours.
this is my code example.
javascript.js
var alertLabel = document.getElementById("alertLabel");
var less = document.getElementById("lessThan").value.replace(":", "");
var late = document.getElementById("timeIn").value.replace(":", "");
var duration = parseInt(document.getElementById("Duration").value);
var outs = document.getElementById("timesOut").value.replace(":", "");
var lessInt = parseInt(less);
var lateInt = parseInt(late);
var outsInt = parseInt(outs);
var durationOut = outsInt + duration; // this will be exceed
var durationIn = lateInt + duration; // this will be exceed
function getAlert() {
let times = new Date();
let sh = times.getHours() + "";
let sm = times.getMinutes() + "";
let ss = times.getSeconds() + "";
let shLong = sh.length == 1 ? "0" + sh : sh;
let smLong = sm.length == 1 ? "0" + sm : sm;
let ssLong = ss.length == 1 ? "0" + ss : ss;
let shSm = shLong + smLong;
document.getElementById("clock").innerHTML = shLong + ":" + smLong + ":" + ssLong;
if (shSm >= outsInt && shSm < durationOut) {
alertLabel.innerHTML = "OUT!!";
} else if (shSm >= lessInt && shSm < lateInt) {
alertLabel.innerHTML = "hurry up, don't be late!!";
} else if (shSm >= lateInt && shSm < durationIn) {
alertLabel.innerHTML = "LATE!!";
} else {
if (shLong >= 21 || shLong <= 4) {
alertLabel.innerHTML = "good dream tonight !!";
} else if (shLong >= 5 && shLong <= 11) {
alertLabel.innerHTML = "spirit Morning !!";
} else if (shLong >= 12 && shLong <= 17) {
alertLabel.innerHTML = "happy Noon !!";
} else if (shLong >= 18 && shLong <= 20) {
alertLabel.innerHTML = "nice evening !!";
}
}
}
<!doctype html>
<html>
<head>
<title></title>
</head>
<body onload="getAlert();setInterval('getAlert()',1000)">
<span id="clock"></span>
<span id="alertLabel"></span>
<div></div>
<input class="" type="text" id="lessThan" value="13:45" name="lessThan"> <!-- when time to in is near -->
<input class="" type="text" id="timeIn" value="13:48" name="timeIn"> <!-- time in and get alert Late -->
<input type="text" id="timesOut" value="13:55" name="timesOut"> <!-- value time to out and get alert Out -->
<input type="text" name="Duration" id="Duration" value="5"> <!-- duration alert for id timeIn and timesOut if more than 100 is the problem, this input as minute -->
</body>
</html>
this is my last try, example in input id timeIn
var a = document.getElementById("timeIn").value.split(":");
for (var i = 0; i < duration; i++){
var b = parseInt(a[0]); // this for hours
var c = parseInt(a[1]); // this for minutes
var x = c + i;
if (x >= 60){
var n = b + 1;
x = x-60;
}
console.log(x);
}
in my last try, in log var x return to zero just once
and the question is, if input value with id duration more than 100, how looping, if each var x reach value (60) his return to zero and var c plus 1 each var x reach 60.
maybe anyone have an easier one to solve this case.
sorry if the explanation is unclear.

How can I find the difference between two time fields and add the result in the same document, inside a collection at MongoDB?

I am using the below function to add one row to the table. If user click Add-row button the below function will get called and one row will be added. In that row user have to enter start and end time .
Now my question is how to calculate the total time from that start and end time like we will calculate in Excel.
I know how they are doing in Excel but how to do the same thing in the table like this ?
I am using node + MongoDB for rendering pages.
var count=0;
function addRow(tableID) {
var id = "newlyaddedrow" + count;
var users = document.getElementById(tableID);
var row = `<tr class="info" style="cursor: pointer;background-color: #dbedf8;" id="${id}">
<td><input id="workAllocation_DateID" type="date" class="form-control" name="#date" value=""/></td>
<td><input type="text" class="form-control" name="#project_ID" value=""/></td>
<td><input type="text" class="form-control" name="#issue_Summary" value=""/></textarea></td>
<td><input type="text" class="form-control" name="#short_Description" value=""/></textarea></td>
<td><input type="time" class="form-control" name="#start_Time" value=""/></td>
<td><input type="time" class="form-control" name="#end_Time" value=""/></td>
<td><input type="time" class="form-control" name="#total_Time" value=""/></td>
</tr> `;
count++;
}
Below structure I have in mongoose collection.
And I want to calculate that total_time when the user enter start_time and end_time.
project_ID:"xxxx"
issue_Summary:"aaaa"
short_Description:"aaaa"
start_Time:"02:02"
end_Time:"03:02"
total_Time:""
_id:5d0ca14e138a7628948804af
date:2019-06-21 05:30:00.0001
Is there any way to do this? Can someone help me in this ?
As long as you store start_time and end_time as strings, you can parse them as dates and calculate the total time. Then convert back to string:
var start_Time = "02:02";
var end_Time ="03:05";
// Parsing as dates using a common date
var start_dt = new Date("1/1/1900 " + start_Time);
var end_dt = new Date("1/1/1900 " + end_Time);
// Calculate difference
var total_dt = end_dt - start_dt;
// Convert total_dt (which is in miliseconds) to hours and minutes
total_dt = total_dt/1000;
var sec = Math.floor(total_dt % 60);
total_dt = total_dt/60;
var min = Math.floor(total_dt % 60);
total_dt = total_dt/60;
var hours = Math.floor(total_dt % 24);
console.log( hours +":" + min)
I have tried with event and it's working perfect.
This event is happening onblur() of the that particular column in the row
function calculateTime(){
var startTime = new Date();
var endTime = new Date();
var totalTime = new Date();
var startTimeStr = '';
var endTimeStr = '';
var totalTimeStr = '';
if(event.target.name == '#start_Time' && event.target.value != ''){
startTimeStr = event.target.value;
if((event.target.parentElement.nextElementSibling.firstElementChild).value != ''){
endTimeStr = (event.target.parentElement.nextElementSibling.firstElementChild).value;
}
}else if(event.target.name == '#end_Time' && event.target.value != ''){
endTimeStr = event.target.value;
if((event.target.parentElement.previousElementSibling.firstElementChild).value != ''){
startTimeStr = (event.target.parentElement.previousElementSibling.firstElementChild).value;
}
totalTimeStr = (event.target.parentElement.nextElementSibling.firstChild);
}
if(startTimeStr != '' && endTimeStr!= ''){
startTime = startTime.setHours(startTimeStr.split(':')[0],startTimeStr.split(':')[1]);
endTime = endTime.setHours(endTimeStr.split(':')[0],endTimeStr.split(':')[1]);
if(startTime > endTime){
alert('End time cannot be before start time!!!');
}else{
totalTime = endTime - startTime;
var hours = Math.floor(((totalTime / (1000*60*60)) % 24));
var minutes = Math.floor(((totalTime / (1000*60)) % 60));
totalTimeStr.value = hours +':'+ minutes;
console.log('Total Time' +totalTimeStr);
}
}
}

multiple alarm clock in javascript using dynamic generated input elements in javascript

I am trying to make a web page which will allow to set multiple alarms using dynamic element creation property of javascript but I'm not able to get the values of these multiple elements and create a alert on that time.
This is my code so far
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br />
<input id="btnAdd" type="button" value="add" onclick="AddTextBox();" />
<script type="text/javascript">
var room = 0;
var i = 0;
function GetDynamicTextBox(){
return '<div>Alarm ' + room +':</div><input type="number"style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" placeholder="hour" id="a'+room+'" /><input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" /><input type="date" style="margin:auto;text-align:center; width:200px; padding:10px"><input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var html = "";
html += "<div>" + GetDynamicTextBox() + "</div>";
document.getElementById("TextBoxContainer").innerHTML = html;
room++;
}
window.onload = RecreateDynamicTextboxes;
function AddAlarm(values){
var hour = document.getElementById('');
var minute = document.getElementById('');
var date = document.getElementById('');
}
</script>
To create a notification whenever a given time or state is reached, I think you are looking for setInterval (see reference).
This method allows you to take action at a regular interval and it tries to honor that interval the best it can. It opens to a common mistake if your action can take longer than that interval duration so be careful not using a too short interval. In such case, actions can overlap and weird behavior will occur. You do not want that to happen so don't be too greedy when using that.
For an alarm project, I would recommend an interval of one second.
Example (not tested):
JavaScript
var alarmDate = new Date();
alarmDate.setHours(7);
alarmDate.setMinutes(15);
// set day, month, year, etc.
var ONE_SECOND = 1000; // miliseconds
var alarmClock = setInterval(function() {
var currentDate = new Date();
if (currentDate.getHours() == alarmDate.getHours() &&
currentDate.getMinutes() == alarmDate.getMinutes()
/* compare other fields at your convenience */ ) {
alert('Alarm triggered at ' + currentDate);
// better use something better than alert for that?
}, ONE_SECOND);
To add dynamic alarms, you could put them into an array then have your setInterval iterate over it.
In the long run you will probably get sick of alert and feel the need to use something that doesn't break the flow of your application. There are a lot of possibilities, one being the use of lightboxes that could stack over each other. That way you would be able to miss an alarm and still be notified by the next one.
Hope this helps and good luck!
You forgot the ID attribute on the date input and you were collecting the input elements in AddAlarm instead of their values.
EDIT: To check the alarms you have to store them and check every minute, if the current date matches one of the alarms. I added a short implementation there.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br />
<input id="btnAdd" type="button" value="add" onclick="AddTextBox();" />
<script type="text/javascript">
var alarms = {};
var room = 0;
var i = 0;
setInterval(function() {
var current = new Date();
for (var nr in alarms) {
var alarm = alarms[nr];
console.log("checking alarm " + nr + " (" + alarm + ")");
if(current.getHours() == alarm.getHours()
&& current.getMinutes() == alarm.getMinutes()) { // also check for day, month and year
alert("ALERT\n"+alarm);
} else{
console.log('Alarm ' + nr + '('+alarm+') not matching current date ' + current);
}
}
}, 60000);
function GetDynamicTextBox(){
return '<div>Alarm ' + room +':</div><input type="number"style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" placeholder="hour" id="a'+room+'" /><input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" /><input type="date" style="margin:auto;text-align:center; width:200px; padding:10px" id="c'+room+'"><input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var html = "";
html += "<div>" + GetDynamicTextBox() + "</div>";
document.getElementById("TextBoxContainer").innerHTML = html;
room++;
}
window.onload = RecreateDynamicTextboxes;
function AddAlarm(values){
var hour = $('#a'+values).val();
var minute = $('#b'+values).val();
var date = $('#c'+values).val();
console.log(hour + ':' + minute + ' on ' + date);
var dateObj = new Date(date);
dateObj.setMinutes(minute);
dateObj.setHours(hour);
console.log(dateObj);
alarms[values] = dateObj;
}
</script>
So far I'm able to generate a alert when the values match the system time but I don't know how to delete the array value when an element is deleted. I am not able to do it. This is my code so far:
<script type="text/javascript">
var snd = new Audio("clock.mp3"); // buffers automatically when created
// Get
if (localStorage.getItem("test")) {
data = JSON.parse(localStorage.getItem("test"));
} else {
// No data, start with an empty array
data = [];
}
var today = new Date();
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
//since page reloads then we will just check it first for the data
function check() {
//current system values
console.log("inside check");
//if time found in the array the create a alert and delete that array object
for(var i = 0; i < data.length; i++) {
var today = new Date();
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
if (data[i].hours == h && data[i].minutes == m && data[i].dates == d ) {
data.splice(i,1);
localStorage["test"] = JSON.stringify(data);
snd.play();
alert("Wake Up Man ! Alarm is over ");
}
}
if((data.length)>0)
{
setTimeout(check, 1000);
}
}
//we do not want to run the loop everytime so we will use day to check
for(var i =0 ; i< data.length; i++)
{
if((data[i].dates == d) && (data[i].hours >= h) && (data[i].minutes >= m) )
{
check();
}
}
console.log(data);
var room = 1;
//var data = [];
var i = 0;
function GetDynamicTextBox(){
var date = new Date();
var h = date.getHours();
var m = date.getMinutes();
var d = date.getDay();
return '<div>Alarm ' + room +':</div><input type="number" style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" value ='+h+' placeholder="hour" id="a'+room+'" /> <input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" value ='+m+' /> <select id="c'+room+'" style="margin:auto; width:150px; padding:10px; color: black" required> <option value="1">Monday</option> <option value="2">Tuesday</option> <option value="3">Wednesday</option> <option value="4">Thursday</option> <option value="5">Friday</option> <option value="6">Saturday</option> <option value="0">Sunday</option> </select> <input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
}
function AddTextBox() {
room++;
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var html = "";
html += "<div>" + GetDynamicTextBox() + "</div>";
document.getElementById("TextBoxContainer").innerHTML = html;
}
window.onload = RecreateDynamicTextboxes;
function AddAlarm(values){
var hour = $('#a'+values).val();
var minute = $('#b'+values).val();
var date = $('#c'+values).val();
//get the current time and date
var today = new Date();
//current system values
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
//first check that whether a same date present in the array or not then push it
var found = -1;
for(var i = 0; i < data.length; i++) {
if (data[i].hours == hour && data[i].minutes == minute && data[i].dates == date ) {
found = 0;
break;
}
}
//if value does not present then push it into the array
if(found == -1)
{
data.push({hours: hour, minutes: minute, dates: date});
//storing it into localstorage
localStorage.setItem("test", JSON.stringify(data));
}
else
{
alert("Same value Exists");
}
//console.log(data);
function check() {
//current system values
//console.log("inside check");
//if time found in the array the create a alert and delete that array object
for(var i = 0; i < data.length; i++) {
var today = new Date();
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
if (data[i].hours == h && data[i].minutes == m && data[i].dates == d ) {
data.splice(i,1);
snd.play();
alert("Wake Up Man ! Alarm is over ");
}
}
if((data.length)>0)
{
setTimeout(check, 1000);
}
}
//we do not want to run the loop everytime so we will use day to check
for(var i =0 ; i< data.length; i++)
{
if((data[i].dates == d) && (data[i].hours >= h) && (data[i].minutes >= m))
{
check();
}
}
}
</script>

Populate HTML table from Javascript array

I would like to take data from a Javascript array and place it into an HTML table. A Javascript file, including arrays and basic functions, was provided. I want to put the array data into my HTML table by calling the functions. The following Javascript was given:
var subject = ['Call Your Mother', 'Cheap Online Meds', 'Change Your Life Today', 'Sppoky Stories', 'Meet Singles In Your Area', 'Have You Heard?', 'Yo', 'RE: Looking for a three legged cat', 'Get Rich Quick!', 'FW: Token Chain Email'];
var sender = ['Mary Monster', 'Dave Danger', 'Spam Master', 'Spike Spurner', 'Ray Ranger', 'Catherine Chaos', 'Van Pire', 'Andy Argye', 'Rick Roger', 'Sue Mee'];
var body = ['Message 1','Message 2','Message 3','Message 4','Message 5','Message 6','Message 7','Message 8','Message 9','Message 10'];
function loadGeeMails(){
for (var i = 0; i < 10; i++){
var message = generateMessage();
window.geemails.push(message);
}
}
function generateMessage(date){
var message = {};
message.date = date || getRandomDate();
message.subject = getRandomElement(subject);
message.sender = getRandomElement(sender);
message.body = getRandomElement(body);
return message;
}
function getRandomElement(arr){
return arr[Math.floor(Math.random() * arr.length)];
}
function getNewMessage(){
var now = new Date();
return generateMessage(now);
}
function getRandomDate(){
var year = 2013;
var month = Math.floor(Math.random() * 12) + 1;
var day = Math.floor(Math.random() * 30) + 1;
var hours = Math.floor(Math.random() * 12) + 1;
var minutes = Math.floor(Math.random() * 59) + 1;
return new Date(year, month, day, hours, minutes);
}
//load intial GeeMail data to window object
(function(){
window.geemails = [];
loadGeeMails();
})();
I want to use those arrays and/or functions to populate the HTML table below:
<html>
<head>
<Title>Kevin Gee-mail Challenge</title>
<script src="js/mail-generator.js"></script>
<link href="css/style.css" rel="stylesheet" media="screen">
<script>
window.onload = function(){
//Call javascript here
};
</script>
</head>
<body>
<div class="container" id="main"></div>
<h1>This is your inbox.</h1>
<table>
<tr>
<th>Date</th>
<th>Sender</th>
<th>Subject</th>
<th>Body</th>
</tr>
<tr>
<td class="date"></td>
<td class="sender"></td>
<td class="subject"></td>
<td class="body"></td>
</tr>
</table>
</body>
</html>
var subject = ['Call Your Mother', 'Cheap Online Meds', 'Change Your Life Today', 'Sppoky Stories', 'Meet Singles In Your Area', 'Have You Heard?', 'Yo', 'RE: Looking for a three legged cat', 'Get Rich Quick!', 'FW: Token Chain Email'];
var sender = ['Mary Monster', 'Dave Danger', 'Spam Master', 'Spike Spurner', 'Ray Ranger', 'Catherine Chaos', 'Van Pire', 'Andy Argye', 'Rick Roger', 'Sue Mee'];
var body = ['Message 1','Message 2','Message 3','Message 4','Message 5','Message 6','Message 7','Message 8','Message 9','Message 10'];
function loadGeeMails(){
for (var i = 0; i < 10; i++){
var message = generateMessage();
window.geemails.push(message);
}
}
function generateMessage(date){
var message = {};
message.date = (date || getRandomDate()).toDateString();
message.subject = getRandomElement(subject);
message.sender = getRandomElement(sender);
message.body = getRandomElement(body);
return message;
}
function getRandomElement(arr){
return arr[Math.floor(Math.random() * arr.length)];
}
function getNewMessage(){
var now = new Date();
return generateMessage(now);
}
function getRandomDate(){
var year = 2013;
var month = Math.floor(Math.random() * 12) + 1;
var day = Math.floor(Math.random() * 30) + 1;
var hours = Math.floor(Math.random() * 12) + 1;
var minutes = Math.floor(Math.random() * 59) + 1;
return new Date(year, month, day, hours, minutes);
}
$("document").ready(function(){
window.geemails = [];
loadGeeMails(); console.log(window.geemails);
$("#emailTemplate").tmpl(window.geemails).appendTo("#emailContainer");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
<body>
<div class="container" id="main"></div>
<h1>This is your inbox.</h1>
<table>
<tr>
<th>Date</th>
<th>Sender</th>
<th>Subject</th>
<th>Body</th>
</tr>
<tbody id="emailContainer">
</tbody>
</table>
<!-- This is the template -->
<script id="emailTemplate" type="text/x-jquery-tmpl">
<tr>
<td> ${date} </td>
<td> ${sender} </td>
<td> ${subject} </td>
<td> ${body} </td>
</tr>
</script>
Here is the better way of doing it just use the JQuery template bindings and this could be real easy and clean.Please find the JSfiddle JSFiddle
JS Fiddle link http://jsfiddle.net/cc44s778/
Create a function that will iterate over window.geemails and create tr elements which will append to the table in question. For example :-
function createTableRows(){
for(var i=0; i < window.geemails.length; i++){
var obj = window.geemails[i];
var trElm = document.createElement('tr');
var dateTdElm = document.createElement('td');
var dateTxt = document.createTextNode(obj.date);
dateTdElm.appendChild(dateTxt);
var senderTdElm = document.createElement('td');
var senderTxt = document.createTextNode(obj.sender);
senderTdElm.appendChild(senderTxt);
var subjectTdElm = document.createElement('td');
var subjectTxt = document.createTextNode(obj.subject);
subjectTdElm.appendChild(subjectTxt);
var bodyTdElm = document.createElement('td');
var bodyTxt = document.createTextNode(obj.body);
bodyTdElm.appendChild(bodyTxt);
trElm.appendChild(dateTdElm);
trElm.appendChild(senderTdElm);
trElm.appendChild(subjectTdElm);
trElm.appendChild(bodyTdElm);
document.tables[0].appendChild(trElm);
}
}
However, I would suggest using datatables or a js library (if possible) for such requirements.
- good luck

Age Calculator in Javascript [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 11 months ago.
Improve this question
I have this codes, this code must be able to compute the age of the user and It must be displayed on the text box provided and the age must change if the user changed his birth-date.
but this code does not work, it doesn't display the computed age in the textbox.
<input name= "date" type="text" readonly="readonly" />
<select id="Ultra" onchange="run()">
<option value="11/15/991">1991-11-15</option>
<option value="10/23/1992">1992-10-23</option>
</select><br><br>
TextBox1<br>
<input type="text" id="srt" placeholder="get value on option select" readonly="readonly"><br>
<script type="text/javascript">
function run() {
var birth = document.getElementById("Ultra").value;
var check = new Date();
var milliDay = 1000 * 60 * 60 * 24;
var AgeinDay = (check - birth) / milliday;
var ComputAge = Math.floor(AgeinDay / 365 );
var age = ComputAge / 365;
document.getElementById("srt").value = age;
}
</script>
Here is a look to complete Age Calculation in JavaScript:
<body onload="getAge()">
<h1 id="age" ></h1>
<script>
function calculateAge(dob) {
var now = new Date();
var dob = new Date(dob);
var year=now.getYear()-dob.getYear();
var month=now.getMonth()-dob.getMonth();
if(month<0){
month=now.getMonth()+12-dob.getMonth();
year=year-1;
}
var day=now.getDate()-dob.getDate();
if(day<0){
var monthNumber=dob.getMonth();
var fullDate=getFullDate(monthNumber);
day=now.getDate()+fullDate-dob.getDate();
month=month-1;
}
return year+" Years, "+month+" Months, "+day+" Days!";
};
function getFullDate(x){
switch(x){
case 0:
return 31;
break;
case 1:
return 28;
break;
case 2:
return 31;
break;
case 3:
return 30;
break;
case 4:
return 31;
break;
case 5:
return 30;
break;
case 6:
return 31;
break;
case 7:
return 31;
break;
case 8:
return 30;
break;
case 9:
return 31;
break;
case 10:
return 30;
break;
case 11:
return 31;
}
}
function getAge(){
x=prompt("Please Enter Your Date of Birth in format (yyyy-mm-dd): ","");
x=new Date(x);
document.getElementById("age").innerHTML="Your age is: "+calculateAge(x);
}
</script>
</body>
try this..
function run() {
var birth = new Date(document.getElementById("Ultra").value);
var curr = new Date();
var diff = curr.getTime() - birth.getTime();
document.getElementById("srt").value = Math.floor(diff / (1000 * 60 * 60 * 24 * 365.25));
}
There were three errors in your code, see the comments inline below:
The year value of first option was 991 instead of 1991, might cause you to think the calculation is wrong.
String containing date that is being assigned to birth variable has to be passed as parameter to Date() function to create a date object that can be used with the current date object below it.
Variable milliDay was declared, then you were trying to use milliday (wrong case D).
<input name= "date" type="text" readonly="readonly" />
<select id="Ultra" onchange="run()">
<option value="11/15/1991">1991-11-15</option> <!-- year value was 991 instead of 1991, might cause you to think the calculation is wrong -->
<option value="10/23/1992">1992-10-23</option>
</select><br><br>
TextBox1<br>
<input type="text" id="srt" placeholder="get value on option select" readonly="readonly"><br>
<script type="text/javascript">
function run() {
var birth = new Date(document.getElementById("Ultra").value); //string containing date has to be passed as parameter to Date() function to create a date object that can be used with the current date object below
var check = new Date();
var milliDay = 1000 * 60 * 60 * 24;
var AgeinDay = (check - birth) / milliDay; //variable here was milliday all small case, declared above as milliDay with a capital D
var ComputAge = Math.floor(AgeinDay / 365 );
var age = ComputAge / 365;
document.getElementById("srt").value = age;
}
</script>
This will return the following values assuming the first option is selected:
age: 0.057534246575342465
ComputAge: 21
Are you just trying to get the age in years, or months, days hours too?
Below is Advanced code for Age calculator in JavaScript
<h1>Age Calculator Tool</h1>
<h2>Hey Dear, What's your name? <br /><input type = "text" placeholder = "Enter Your Name" autofocus/></h2>
<div id = "disBlock">
<p id = "disBD"></p>
<p id = "display"></p>
<p id = "time"></p>
</div>
<div id = "postCredit">
<p id = "credit"></p>
<a id = "about" href="#" target="_blank">Know More About Me</a>
</div>
<form>
<label>Enter Your Date of Birth: <input
type = "date"/></label><br />
<button type = "button">Calculate</button>
<button type = "reset">Reset</button>
</form>
<script>
let display = document.getElementById("display");
let input = document.getElementsByTagName("input");
let button = document.getElementsByTagName("button");
let time = document.getElementById("time");
let disBlock = document.getElementById("disBlock");
let disBD = document.getElementById("disBD");
let creditBlock = document.getElementById("postCredit");
let credit = document.getElementById("credit");
let about = document.getElementById("about");
disBlock.style.display = "none";
creditBlock.style.display = "none";
let dob = new Date(), today = new Date(), calTime;
function samay() {
let d = new Date();
time.innerHTML = d.getHours() + " Hours, " +
d.getMinutes() + " Minutes, " + d.getSeconds() + " Seconds Old";
}
function calculate() {
disBlock.style.display = "block";
creditBlock.style.display = "block";
credit.innerHTML = "Thank You For Visiting<br>Our website website.com";
let x = input[1].value.split("-");
dob.setDate(x[2]);
dob.setMonth(x[1] - 1);
dob.setFullYear(x[0]);
let year, month, day, HBD;
day = (function() {
if(today.getDate() > dob.getDate()) {
return today.getDate() - dob.getDate() - 1;
}
else if(today.getDate() == dob.getDate()) {
return today.getDate() - dob.getDate();
}
else {
let calDate = new Date(dob.getFullYear(), dob.getMonth() + 1, 0);
return (today.getDate() + calDate.getDate()) - dob.getDate() - 1;
}
}());
month = (function() {
if(today.getMonth() >= dob.getMonth()) {
if(today.getDate() >= dob.getDate()) {
return today.getMonth() - dob.getMonth();
}
else {
if((today.getMonth() - 1) >= dob.getMonth()) {
return (today.getMonth() - 1) - dob.getMonth();
}
else {
return ((today.getMonth() - 1) + 12) - dob.getMonth();
}
}
}
else {
if(today.getDate() >= dob.getDate()) {
return (today.getMonth() + 12) - dob.getMonth();
}
else {
return ((today.getMonth() - 1) + 12) - dob.getMonth();
}
}
}());
year = (function() {
if(dob.getMonth() == today.getMonth()) {
if(dob.getDate() > today.getDate()) {
return (today.getFullYear() - 1) - dob.getFullYear();
}
else {
return today.getFullYear() - dob.getFullYear();
}
}
else {
if(dob.getMonth() > today.getMonth()) {
return (today.getFullYear() - 1) - dob.getFullYear();
}
else {
return today.getFullYear() - dob.getFullYear();
}
}
}());
HBD = (function(){
if(today.getMonth() == dob.getMonth()) {
if(today.getDate() == dob.getDate()) {
disBD.innerHTML = "OMG it's your Birthday<br>Happy Birthday To You<br>";
}
else {
disBD.innerHTML = "";
}
}
else {
disBD.innerHTML = "";
}
}());
display.innerHTML = "Hi Dear " + input[0].value + ", <br/>You are " + year + " Years, " + month +
" Months, " + day + " Days, ";
calTime = setInterval(samay, 1000);
}
button[0].onclick = calculate;//when calculate button is clicked
function reset() {
input[0].focus();
display.innerHTML = "";
time.innerHTML = null;
clearInterval(calTime);
disBlock.style.display = "none";
creditBlock.style.display = "none";
}
button[1].onclick = reset;//when the reset button is clicked
</script>
More source code from : https://www.technicalarp.com/2021/11/javascript-age-calculator-script-html-code.html

Categories

Resources