Compare date and string with jquery - javascript

I'm trying to compare today date and the date from the string. They both has a string type. Why do I get "no!" ?
jQuery(document).ready(function () {
Date.prototype.today = function () {
return ((this.getDate() < 10) ? "0" : "") + this.getDate() + "/" +(((this.getMonth() + 1) < 10) ? "0" : "") + (this.getMonth() + 1) + "/" + this.getFullYear();
}
datetodayvar = new Date().today();
deadlinadate = '16/10/2016';
if (String(datetodayvar) >= String(deadlinadate)) {
alert("yes!");
} else {
alert("no!");
}
});

Turn them both to Date objects instead of strings.
jQuery(document).ready(function () {
Date.prototype.today = function () {
return ((this.getDate() < 10)?"0":"") + this.getDate() +"/"+(((this.getMonth()+1) < 10)?"0":"") + (this.getMonth()+1) +"/"+ this.getFullYear();
}
datetodayvar = new Date().today();
deadlinadate = '02/11/2016';
if(new Date(datetodayvar) >= new Date(deadlinadate)) {
alert("yes!");
} else {
alert("no!");
} });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If you have your "date string" from 3 different input fields(dropdowns or whatever) don't input a string, but make the date format as follows.
var year = 2015;
var month = 2-1; // February
var day = 27;
var now = new Date(year, month, day);
That way, you don't have to worry about date notation, localisation, if you need to use a - a . or / or something else inbetween.
Also remember the month, is always -1 because it starts counting as 0(januari being 0, december being 11.
Also, keep mind of day light savings time. That might go hayward with your freshly minted date objects too by subtracting an hour.
The snippet below has all the things i'd use in a "simple" comparing mechanism.
jQuery(document).ready(function () {
var str = '';
for(var c=1;c<32;c++) {
str += '<option value="'+c+'">'+c+'</option>';
}
$('#day').html(str);
var str = '';
for(var c=0;c<12;c++) {
str += '<option value="'+c+'">'+(c+1)+'</option>';
}
$('#month').html(str);
var str = '';
for(var c=parseInt(new Date().getFullYear());c>1990;c--) {
str += '<option value="'+c+'">'+c+'</option>';
}
$('#year').html(str);
$('#istodaycheck').on('click',function() {
var day = $('#day').get(0);
var month = $('#month').get(0);
var year = $('#year').get(0);
var date = new Date(
year.options[year.selectedIndex].value,
month.options[month.selectedIndex].value,
day.options[day.selectedIndex].value);
date.correctDst();
$('#output').text(date.isToday() ? 'yes' : 'no');
});
});
/**
* Retrieve standard timezome offset
*/
Date.prototype.stdTimezoneOffset = function() {
var jan = new Date(this.getFullYear(), 0, 1);
var jul = new Date(this.getFullYear(), 6, 1);
return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}
/**
* Checks if date is in day lights savings
*/
Date.prototype.dst = function() {
return this.getTimezoneOffset() < this.stdTimezoneOffset();
}
/**
* corrects the unwanted substraction of an hour on fresh dates.
*/
Date.prototype.correctDst = function() {
if(!this.dst()) {
this.setHours(this.getHours()+1);
}
}
/**
* Returns a date instance without time components.
*/
Date.prototype.justDate = function() {
var date = new Date(this.getFullYear(),this.getMonth(),this.getDate());
date.correctDst();
return date;
}
/**
* Tests if given date is today.
*/
Date.prototype.isToday = function() {
// strip possible time part.
var testdate = this.justDate();
var datetodayvar = new Date().justDate();
return datetodayvar.getTime() == testdate.getTime()
}
#output {
background-color: #eee;
border: 1px solid pink;
display: block;
width: 100%;
height:200px;
text-align: center;
font-size:121pt;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="day">
</select>
<select id="month">
</select>
<select id="year">
</select>
<button id="istodaycheck">Is this date today?</button>
<div id="output">
</div>

When comparing dates, always work with Date objects. The caveat with this is that when creating the objects, the provided date strings have to be in d/m/y or d-m-y format. Also note that today is not 16/10/2016.
jQuery(document).ready(function() {
var datetodayvar = new Date();
var deadlinadate = new Date('2/11/2016');
if (datetodayvar >= deadlinadate) {
console.log("yes!");
} else {
console.log("no!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

First of all you are wrongly comparing two strings as if they were the numbers, when you do like this,
if(String(datetodayvar) >= String(deadlinadate)) { }
because if you want to compare strings you would have to
if(String(datetodayvar).equals(String(deadlinadate))){...
otherwise you compare the memory locations and not actual values.
Read more What is the difference between == vs equals() in Java?
This code will check whether the two string objects are greater than or equal to each other alphabetically, and not according to your actual requirement of date comparision. The functional code would be like this:
jQuery(document).ready(function () {
Date.prototype.today = function () {
return ((this.getDate() < 10)?"0":"") + this.getDate() +"/"+(((this.getMonth()+1) < 10)?"0":"") + (this.getMonth()+1) +"/"+ this.getFullYear();
}
datetodayvar = new Date().today();
deadlinadate = '02/11/2016';
if(new Date(datetodayvar) >= new Date(deadlinadate)) {
console.log("yes!");
} else {
console.log("no!");
} });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Assuming date format as dd/mm/yyyy and that deadline >= today
var ar = '02/11/2016'.split('/').map(Number);
var valid = new Date(ar[2],ar[1]-1,ar[0]) >= new Date().setHours(0,0,0,0);
console.log(valid);

Related

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>

How to stop incorrect value in datepicker when previous data select in JavaScript?

Here, I got code for disable date in datepicker. when user select previous date then it alert to put a valid future date. It's working.
But It's printing whatever we select previous date. I want to stop print when previous date select. Thanks in advance.
<div class="col-md-8">
<input class="form-control datepicker" id="datepicker" onchange="checkDate()" required type="date" name="smexdate" value="<?=$promotion_details['expiry_date']?>" data-date-format="yyyy-mm-dd">
</div>
and JavaScript below.
function checkDate() {
var selectedText = document.getElementById('datepicker').value;
var selectedDate = new Date(selectedText);
var now = new Date();
if (selectedDate < now)
{
alert("Date must be in the future");
return false;
}
}
How about this?
var lastData;
function checkDate() {
var selectedText = document.getElementById('datepicker').value;
var selectedField = document.getElementById('datepicker');
var selectedDate = new Date(selectedText);
var now = new Date();
if (selectedDate < now)
{
console.log(lastData)
selectedField.value = (lastData) ? lastData : '';
alert("Date must be in the future");
return 0;
}
var theDate = new Date(selectedText);
var month = theDate.getMonth() + 1;
var date = theDate.getDate();
var year = theDate.getFullYear();
lastData = year + "-" + String("0" + month).slice(-2) + "-" + String("0" + date).slice(-2);
}

How I can interpret the correct date in Javascript when the year is of the format yy?

I have defined an input that accepts only dates in HTML.
The user can enter the date manually or by using a Calendar which is defined in javascript.
I am using Javascript and Jquery to convert the input to a date:
var lStartDateText = $j("#DateStarte").val();
var lEndDateText = $j("#DateEnd").val();
var lEffStartDate = new Date(lStartDateText);
var lEffEndDate = new Date(lEndDateText);
My problem is that when the user enters the following date manually 1/1/50 is interpreted as 1/1/1950 but 1/1/49 is interpreted as 1/1/2049. I want it always to be interpreted as 20xx.
On the other hand the Calendar allows the user to choose a year from 2006 to 2021 in case the user wants to choose a date from it and not enter it manually.
Hope I can get some help here ??
Try this
var lStartDateText = $j("#DateStarte").val();
var lEndDateText = $j("#DateEnd").val();
var lEffStartDate = ReFormatDate(lStartDateText);
var lEffEndDate = ReFormatDate(lEndDateText);
function ReFormatDate(dateString) {
var dateParts = dateString.split("/");
if (dateParts[2].length === 2) {
dateParts[2] = "20" + dateParts[2];
}
return new Date(dateParts.join("/"));
}
use this
var lStartDateText = "1/1/50" ;
var lEndDateText = "1/1/49" ;
var res = lStartDateText.slice(4);
var starttext = lStartDateText.replace(res,"20"+res);
var res1 = lEndDateText.slice(4);
var endtext = lEndDateText.replace(res1,"20"+res1);
alert(starttext);
alert(endtext);
var lEffStartDate = new Date(starttext);
alert("start date"+lEffStartDate);
var lEffEndDate = new Date(endtext);
alert("End Date"+lEffEndDate);
If you know your getting the last 2 digits of the year (50), and you know you always want to add the first 2 digits, which are constant (20), that's a slight modification to your code:
var lStartDateText = '20' + $j("#DateStarte").val();
var lEndDateText = '20' + $j("#DateEnd").val();
Note that this is not particularly robust, e.g. if the user enters text which is not a date you might end up with a string like '20hi', but that may be outside the scope of your question and it will be parsed as an invalid date.
$('#year').on('change keyup', function() {
var y = $('#year').val();
if (y.length === 2) {
y = '20' + y
}
if (y.length === 4) {
var dateY = new Date();
dateY.setFullYear(y);
$('#result').html(dateY);
} else {
$('#result').html('No YY or YYYY date found');
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label for="year">Enter year (YY or YYYY)</label>
<input id="year" type="text">
<div id="result"></div>
i hope it's will be help you.
$('#year').on('change keyup', function() {
var right_date = $('#year').val();
var data = $('#year').val().split('/');
if (data[2].length == 2){
var twoDigitsCurrentYear = parseInt(new Date().getFullYear().toString().substr(0,2));
$('#result').html(data[0]+'/'+data[1]+'/'+twoDigitsCurrentYear + data[2]);
}
else {
$('#result').html(right_date);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label for="year">Enter year (YY or YYYY)</label>
<input id="year" type="text" placeholder="dd/mm/yy">
<div id="result"></div>

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

Run function for 30 min

Here's what I want to do.
Execute a function : once, at some time of the day.
The function run for 30 minutes.
I've tried setTimeout but it doesn't fit my requirement because it run the function after X millisecond. Whereas I need the function to execute right away, at desired time for 30 minutes. Code as attached.
var d = new Date();
var hour = d.getHours();
var minute = d.getMinutes();
var day = self.getDate();
var month_name=new Array(12);
month_name[0]="January"
month_name[1]="February"
month_name[2]="March"
month_name[3]="April"
month_name[4]="May"
month_name[5]="June"
month_name[6]="July"
month_name[7]="August"
month_name[8]="September"
month_name[9]="October"
month_name[10]="November"
month_name[11]="December"
var month = month_name[self.getMonth()];
var fullDate = month+' '+day+' '+hour+':'+minute;
function someFunction() {}
function closeFunction(){
noticeDiv.css('display', 'block');
mainDiv.css('display', 'none');
}
function executeFunction(targetDate){
if (fullDate == targetDate){
setTimeout ( closeFunction(), 180000 );
}else{
someFunction();
}
}
executeFunction(targetDate);
Use setInterval Function
Syntax-> var interval = setInterval(function(){function_name()},timeout In milliseconds);
To clear Interval or stop function we use ->clearInterval(interval);
HTML
<!-- Hide by default, show at target time -->
<div id="noticeDiv" style="display: none">
<h2>Registration Closed.</h2>
</div>
<!-- Show by default, hide at target time -->
<div id="mainDiv">
<h2>Registration Open.</h2>
</div>
jQuery
$(document).ready(function () {
var d = new Date();
var hour = d.getHours();
var minute = d.getMinutes();
var day = d.getDate();
var month_name = new Array(12);
month_name[0] = "January"
month_name[1] = "February"
month_name[2] = "March"
month_name[3] = "April"
month_name[4] = "May"
month_name[5] = "June"
month_name[6] = "July"
month_name[7] = "August"
month_name[8] = "September"
month_name[9] = "October"
month_name[10] = "November"
month_name[11] = "December"
var month = month_name[d.getMonth()];
var fullDate = month + ' ' + day + ' ' + hour + ':' + minute;
console.log(fullDate);
fulldate = 'May 3 17:1';
function executeFunction(targetDate) {
x = 0;
if (fulldate == targetDate) {
//set closing time of function 180000 = 30 min.It will hide div registration open and show registration closed div.
interval = setInterval(closeFunction, 180000);
} else {
openFunction();
}
}
function openFunction() {
console.log('Registration is now open')
}
function closeFunction() {
x++;
$('#mainDiv').append(x);
if (x == 1) {
$('#noticeDiv').show();
$('#mainDiv').hide();
clearInterval(interval);
}
}
// Execute time
executeFunction('May 3 17:1');
});
Working Demo http://jsfiddle.net/cse_tushar/8r5T8/

Categories

Resources