When running code first two options work "happy birthday" and "you will be turning ____ years old this year" last option will not.
I have tried several different combinations of code, nothing will change for the bottom code else to work
function getAge() {
var today = new Date();
var nowYear = today.getFullYear();
var nowMonth = today.getMonth();
var nowDay = today.getDate();
//prompt user to enter birth year
var birth = prompt("When were you born?", "YYYY-MM-DD");
//calculate if birth month is past present furture
var birth = new
Date(parseInt(birth.substring(0, 4)), parseInt(birth.substring(5, 7)) - 1, parseInt(birth.substring(8, 10)));
var birthYear = birth.getFullYear();
var birthMonth = birth.getMonth();
var birthDay = birth.getDate();
//create user string compare birth year and birth month to present date
var compBirth = birthMonth.toString() + birthDay.toString();
var compToday = nowMonth.toString() + nowDay.toString();
//write evaluation
if (compBirth == compToday) {
document.write('Today is your Birthday! Happy Birthday!');
} else if (compBirth < compToday) {
document.write('You will be turning' + " " + (nowYear - birthYear +
" ") + 'years old later this year');
} else {
document.write('You have turned' + " " + (nowYear - birthYear +
" ") + 'years old already this year');
}
}
getAge();
Need all three results to register output correctly
I fix your code
change calculation compBirth and compToday to compare its as numbers
change condition compBirth < compToday to compBirth > compToday (seems more logic)
function getAge(){
var today = new Date();
var nowYear = today.getFullYear();
var nowMonth = today.getMonth();
var nowDay = today.getDate();
//prompt user to enter birth year
var birth = prompt("When were you born?", "YYYY-MM-DD");
//calculate if birth month is past present furture
var birth = new Date(parseInt(birth.substring(0,4)),parseInt(birth.substring(5,7))-1,parseInt(birth.substring(8,10)));
var birthYear = birth.getFullYear();
var birthMonth = birth.getMonth();
var birthDay = birth.getDate();
//create user string compare birth year and birth month to present date
var compBirth = birthMonth*100 + birthDay;
var compToday = nowMonth*100 + nowDay;
//write evaluation
if( compBirth == compToday) {
document.write('Today is your Birthday! Happy Birthday!');
} else if ( compBirth > compToday){
document.write('You will be turning'+ " " + (nowYear - birthYear
+ " ") + 'years old later this year');
}
else {
document.write('You have turned' + " " + (nowYear - birthYear +
" ") + 'years old already this year');
}
}
getAge();
Your code works fine if the input is empty and you click Ok. It doesn't work only when you click cancel because cancel returns null. For that you can add one more condition like this:
var birth = prompt("OK?");
else if (result === null) {
return;
}
Related
I've created a pirate speak program.
It asks the user for their name and date of birth and calculates the years from the input and added 100 years for fun. I also need to calculate the number of days left until their birthday using user input but I don't know what to do. I've tried some methods and stuff but its not working. any tips or mistakes I need to fix?
var name = prompt('What\'s yer name?');
var date = prompt('What\'s yer date o\' birth? (mm/dd/yyyy)');
let years = date;
let num = years.substring(6, 10);
var myInput = parseInt(num);
var x = myInput;
var y = 100;
var result = x + y;
console.log(`Ahoy, ${name}. It will be th\' year ${result} when ye be 100 years barnacle-covered.`);
var myInput = parseInt(date);
var bday = myInput;
function daysUntilNext(month, day){
var tday= new Date(), y= tday.getFullYear(), next= new Date(y, month-1, day);
tday.setHours(0, 0, 0, 0);
if(tday>next) next.setFullYear(y+1);
return Math.round((next-tday)/8.64e7);
}
var d= daysUntilNext(date);
console.log(d+' day'+(d>1? 's': '')+' until yer birthday');
Ok, I have cleaned up your JavaScript a little. Best practice was to get the date from the string and parse each part then just create a Date object from there. What's easier in the future is to use a datepicker HTML component rather than a string, but I understand that wasn't your goal for this.
Next, do the plus 100 calculation and display that result.
Lastly, take the Date object we made and take the information that we need from it. FWIW getDay() returns the day of the week, you want getDate() which return the day of the month. Then calculate how many days away from those in the next year. Display that result in the console.
I think you were getting that NAN because you were doing calculations on strings not numbers or it was because there weren't enough parameters in daysUntilNext(), so you were operating on null or undefined somewhere
var name = prompt('What\'s yer name?');
var birthDateString = prompt('What\'s yer date o\' birth? (mm/dd/yyyy)');
var daySubstring = birthDateString.substring(3, 5);
var monthSubstring = birthDateString.substring(0, 2);
var yearSubstring = birthDateString.substring(6, 10);
var birthdate = new Date(parseInt(yearSubstring), parseInt(monthSubstring) - 1, parseInt(daySubstring));
var ONE_HUNDRED = 100;
var result = parseInt(yearSubstring) + ONE_HUNDRED;
console.log(`Ahoy, ${name}. It will be th\' year ${result} when ye be 100 years barnacle-covered.`);
function daysUntilNext(month, day) {
var today = new Date();
var year = today.getFullYear();
var next = new Date(year, month, day);
today.setHours(0, 0, 0, 0);
if (today > next) next.setFullYear(year + 1);
return Math.round((next - today) / 8.64e7);
}
var d = daysUntilNext(birthdate.getMonth(), birthdate.getDate());
console.log(d + ' day' + (d > 1 ? 's' : '') + ' until yer birthday');
The other answerer's code is correct, but not clear. Here's the same, only more user-friendly.
The difference is that single-digit months or days won't bother you.
I hope I could help.
var name = prompt('What\'s yer name?');
var birthDateString = prompt('What\'s yer date o\' birth? (mm/dd/yyyy)');
var inputdate = birthDateString.split("/");
var daySubstring = inputdate[1];
var monthSubstring = inputdate[0];
var yearSubstring = inputdate[2];
var birthdate = new Date(parseInt(yearSubstring), parseInt(monthSubstring) - 1, parseInt(daySubstring));
var ONE_HUNDRED = 100;
var result = parseInt(yearSubstring) + ONE_HUNDRED;
console.log(`Ahoy, ${name}. It will be th\' year ${result} when ye be 100 years barnacle-covered.`);
function daysUntilNext(month, day) {
var today = new Date();
var year = today.getFullYear();
var next = new Date(year, month, day);
today.setHours(0, 0, 0, 0);
if (today > next) next.setFullYear(year + 1);
return Math.round((next - today) / 8.64e7);
}
var d = daysUntilNext(birthdate.getMonth(), birthdate.getDate());
console.log(d + ' day' + (d > 1 ? 's' : '') + ' until yer birthday');
I'm building a form to standardize filenames (I'm a video editor). After a lot of research, copying, pasting and testing I'm almost there. I just need to display the current date at the end of the filename after the user clicks on the corresponding checkbox.
The HTML has the code to get the current date and to format it as I want (YYMMDD), but for the life of me I can't find a way to display it at the end of the filename. The code to display the date works because I can enable/disable text, but I can't display the result of the todaysdate function.
This is the code to get the current date and format it to YYMMDD:
function SetDate()
{
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear() - 2000;
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
var today = year + month + day;
document.getElementById('today').value = today;
}
This is the code that adds or removes the date at the end of the filename when you click the checkbox.
function todaysdate()
{
var checkbox = document.getElementById('todayis');
if (checkbox.checked != false)
document.getElementById('todayis').value = "DATE";
if (checkbox.checked != true)
document.getElementById('todayis').value = "";
}
This is the code for the checkbox:
Add date (YYMMDD): <input type="checkbox" onclick="todaysdate()" id="todayis" value="" />
Thanks in advance for your help.
Edit: Added the code.
In your todaysdate function you set the value of the todayis input to DATE, where you should be setting it to the value of your date calculation. Here’s just a little change to what you have that should probably work!
function todaysdate()
{
var checkbox = document.getElementById('todayis');
if (checkbox.checked != false)
document.getElementById('todayis').value = getDate();
else if (checkbox.checked != true)
document.getElementById('todayis').value = "";
}
function getDate()
{
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear() - 2000;
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
var today = year + "" + month + "" + day;
return today;
}
You can also use the php function Time:
Set the timezone:
date_default_timezone_set('America/New_York');
And get the actual date:
$date_now = date('Y/m/d', time());
So, to set the value on the input:
<input type="checkbox" value="<?php echo $date_now ?>" />
function getYYMMDDDate(date) {
var year = String(date.getFullYear()).substring(2,4);
var month = String(date.getMonth() + 1).padStart(2, "0");
var day = String(date.getDate()).padStart(2,"0");
return year + month + day;
}
...
// change this document.getElementById('todayis').value = "DATE";
document.getElementById('todayis').value = getYYMMDDDate(new Date());
I would like to create a function to validate if a DOB date i.e: 10/05/2002 is allowed to register this year 2020, for example if user selects the three dropdowns 10 05 2020(today's date) it should be allowed to register and pass this validation because today turns 18.
Currently code is only validating using year value from Date object and selected year from dropdown.
function myFunction(Year) {//2020
var Year = 2020 > selected dropdown
var month = 10 > selected dropdown
var day = 05 > selected dropdown
//Today's day selected since today user turns 18 years old
var birthdate = month + '/' + day + '/' + Year;
var age = new Date().getFullYear() - new Date(birthdate).getFullYear();
//Day and Month Validation here
if (age <= 18) {
alert('Not Allowed To Register');
}
else {
alert('Allowed to register');
}
}
If dropdown option selections = From January 1st untill today(Oct 05 2020) it should be allowed to register
Validation should be against Day and Month also not just the year to be 18 years old.
This is what I've tried after doing some research and different answers, but boolean value(dob_this_year) in calculateDOB() function still false and not validating correctly.
function MyFunction(year) {
var Year = 2020;
var month = 10;
var day = 05;
var birthdate = month + '/' + day + '/' + Year;
var isAllowedToRegister = calculateDOB(birthdate);
//var age = new Date().getFullYear() - new Date(birthdate).getFullYear();
if (!isAllowedToRegister) {
alert('Allowed to Register');
}
else {
alert('Not Allow to register yet!');
}
}
function calculateDOB(date) {
var now = new Date();
var current_year = now.getFullYear();
var year_diff = current_year - new Date(date).getFullYear();
var birthday_this_year = new Date(current_year, new Date(date).getMonth, new Date(date).getDate());
var dob_this_year = (now >= birthday_this_year);
return dob_this_year ? true : false;
}
I am new to JavaScript with absolutely little idea about the language. I am trying to put an age restriction in a job application form where for the date of birth text field, date format is dd/mm/yyyy and applicants must be at between 15 and 80 years old at the time they fill in the form otherwise they won't be able to apply. I do not want to embed it into HTML file but write it in .js file only.
for DOB input type is text, name is dob, id is dob, pattern is (0[1-9]|1[0-9]|2[0-9]|3[01])/(0[1-9]|1[012])/[0-9]{4}
Thank you.
You can use min and max attributes of HTML5 input date
HTML:
<input type="date" id="txtDate" />
JavaScript :
var dtToday = new Date();
var month = dtToday.getMonth() + 1;
var day = dtToday.getDate();
var year = dtToday.getFullYear();
var maxYear = year - 18;
if(month < 10)
month = '0' + month.toString();
if(day < 10)
day = '0' + day.toString();
var maxDate = maxYear + '-' + month + '-' + day;
var minYear = year - 80;
var minDate = minYear + '-' + month + '-' + day;
alert(maxDate);
document.querySelectorAll("#txtDate")[0].setAttribute("max",maxDate);
document.querySelectorAll("#txtDate")[0].setAttribute("min",minDate);
function processDate(date){
var parts = date.split("/");
return new Date(parts[2], parts[1] - 1, parts[0]);
}
function calcAge(date) {
var dBirth = processDate(date);
var dToday = new Date();
var diff = dToday.getTime() - dBirth.getTime();
return Math.floor(diff / (1000 * 60 * 60 * 24 * 365.25));
}
function validateDate(date){
var age = calcAge(date);
console.log(age);
if(15<=age && age <=80) return true;
else {
return false;
}
}
console.log(validateDate("01/12/1988"));
console.log(validateDate("02/11/1911"));
This is my code and I want to add two days from the current date to the value of a hidden input. If I borrow now, this results in a waiting period of two days. It will be better if I borrow on Friday; Saturdays and Sundays will not count so the waiting period ends on Monday, four days later.
<input type="hidden" name="due_date" id="sd" maxlength="10" style="border: 3px double #CCCCCC;" required/>
You can use JavaScript to add 2 days and For Friday(5) add 4 days to skip Saturday And Sunday plus 2 days:
var currentDate = new Date();
//Checking If Current day is Friday
if(currentDate.getDay() == 5) {
var numberOfDaysToAdd = 4; //Adding 4 to skip sat. & sun. if Friday
} else {
var numberOfDaysToAdd = 2; //Adding 2 days if not Friday
}
currentDate.setDate(currentDate.getDate() + numberOfDaysToAdd);
//Formatting to dd/mm/yyyy :
var dd = currentDate.getDate();
var mm = currentDate.getMonth() + 1;
var y = currentDate.getFullYear();
var someFormattedDate = dd + '/'+ mm + '/'+ y;
// Displaying Fromatted Date
document.getElementById("display").innerHTML = someFormattedDate;
<div id="display"></div>
It has been assumed that nothing is Borrowed on Saturday And Sunday.
The code creates an array of objects referring to the days of the week as well as a Date object oDate used to retrieve the current date information. If the day of the week is not Friday, then user is advised to wait till Friday.
The hidden input "due_date" has its value set to two days from the current date unless that day is Friday in which case the due date becomes 4 days later, to skip the weekend and add the usual 2 days to the waiting period. If the hidden input were part of a form, once it is submitted, and the data validated, assuming submission by POST, one could use variable $_POST["due_date"] in an INSERT query to store that value in a database, making sure to use either mysqli_real_escape_string() or PDO and bound parameters.
Note: I altered the HTML so that both the NAME and ID attributes of the hidden input are both set to "due_date".
var d = document;
d.g = d.getElementById;
var arrDaysOfWeek = {"Sunday":0,"Monday":1,"Tuesday":2,"Wednesday":3,"Thursday":4,"Friday":5,"Saturday":6};
var arrWkDayNames = Object.keys( arrDaysOfWeek );
var oDate = new Date();
var currDay = oDate.getDay();
var md = oDate.getDate();
var mm = oDate.getMonth() + 1;
var y = oDate.getFullYear();
var waitPeriod = 2; // default
var daysTillFriday = (currDay == 0)? arrDaysOfWeek["Friday"]
: arrDaysOfWeek["Friday"] - currDay;
if (currDay == arrDaysOfWeek["Saturday"]) {
daysTillFriday = arrWeekDayNames.length + arrDaysOfWeek["Friday"] - currDay;
}
var mess = "";
if (currDay != arrDaysOfWeek["Friday"] ) {
mess = "\nYou should wait to borrow on Friday, i.e. " + daysTillFriday + " days from today.";
}
if( currDay + 2 != arrDaysOfWeek["Friday"] ) {
daysTillFriday = arrDaysOfWeek["Friday"] - currDay - 2;
mess += "\nSo, best not even in two days. Just wait till Friday which will be in " + daysTillFriday + " days from two days from now.";
}
waitPeriod = (currDay == arrDaysOfWeek["Friday"] )
? 4 //skip sat. & sun. plus 2
: 2; // usual wait period
oDate.setDate(md + waitPeriod);
mess += "\nTo proceed know that the happening date is " + oDate;
//USA date style ...
var date_parts = [ mm, md, y ];
mess += "\nToday is " + arrWkDayNames[ currDay ] + ", " + date_parts.join("/");
d.g("display").textContent = mess;
d.g("due_date").value = oDate;
console.log( "Hidden input due date value: " + d.g("due_date").value );
<div id="display"></div>
<input type="hidden" name="due_date" id="due_date" maxlength="10" style="border: 3px double #CCCCCC;" required/>
You can use JavaScript, no jQuery required:
var someDate = new Date();
var numberOfDaysToAdd = 2;
someDate.setDate(someDate.getDate() + numberOfDaysToAdd);
Formatting to dd/mm/yyyy :
var dd = someDate.getDate();
var mm = someDate.getMonth() + 1;
var y = someDate.getFullYear();
var someFormattedDate = dd + '/'+ mm + '/'+ y;
answer from - How to add number of days to today's date?
You can do it in php
echo date('Y-m-d', strtotime("+2 days"));
Answer From - Add number of days to a date