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"));
Related
I'm trying to create a function that creates a dynamic date range based on the date supplied in a string.
What I've done so far:
Capture date in the string I'm looking to change;
Check to see if that date is a Thursday (if so the range will need to account for the weekend)
What I need to do:
Find a way to get the second date in the range to account for the weekend;
Find a way to make sure that the second date takes into account the last day of the month.
Apologies for old syntax, GTM doesn't like anything using ES6 so I'm a little constrained on this project.
Note I am using DD/MM/YYYY
var regex = /[\d\/\d\/\d]/g;
var text = document.querySelector('.shipmentLineTitle b');
var originalDate = text.innerText.match(regex, "");
if (originalDate.length > 10) {
originalDate.pop();
originalDate.join('');
}
var ogDateString = originalDate.join('');
var dayNumber = originalDate.splice(0, 2).join('');
var monthNumber = originalDate.splice(1, 2).join('');
var yearNumber = originalDate.splice(2, 4).join('');
// if originalDate is a thursday (5) dynamicString will need to be a Monday (1).
var date = new Date(yearNumber, monthNumber -1, dayNumber);
var dynamicDateString = "";
if (date.getDay == 5) {
var newDate = new Date(date) + (86400000 * 3);
var dd = newDate.getDate();
var mm = newDate.getMonth() +1;
var yy = newDate.getFullYear();
dymamicDateString = dd + '/' + mm + '/' + yy;
} else {
var newDate = new Date(date) + 86400000;
var dd = newDate.getDate();
var mm = newDate.getMonth() +1;
var yy = newDate.getFullYear();
dynamicDateString = dd + '/' + mm + '/' + yy;
}
var newContent = 'Delivery will be made between ' + ogDateString + ' - ' + dynamicDateString + '. An accurate delivery date will be provided after you place your order.';
text.innerText = newContent;
<span class="shipmentLineTitle">Delivery details: <b>your delivery will arrive on 09/10/2020 (1 delivery)</b></span>
Thursday is day 4
Here is a simpler script
var textField = document.querySelector('.shipmentLineTitle b'),
text = textField.innerText,
originalDate = text.match(/\d{2}\/\d{2}\/\d{4}/)[0].split("/"),
dayNumber = +originalDate[0],
monthNumber = +originalDate[1],
yearNumber = +originalDate[2],
date = new Date(yearNumber, monthNumber - 1, dayNumber, 15, 0, 0, 0),
aDay = 86400000,
newDate = new Date(date),
day = date.getDay(),
daysToAdd = 1; // Sunday to Wednesday
// if originalDate is a Thursday (4) or Saturday (6), dynamicString will need to be a Monday (1).
if (day === 4) daysToAdd = 4; // Thursday - delivery Monday
else if (day === 6) daysToAdd = 2; // Saturday
newDate.setDate(newDate.getDate() + daysToAdd);
var dd = newDate.getDate(),
mm = newDate.getMonth() + 1,
yy = newDate.getFullYear(),
dynamicDateString = dd + '/' + mm + '/' + yy,
newContent = text + ' - ' + dynamicDateString + '</b>. An accurate delivery date will be provided after you place your order.';
textField.innerHTML = newContent;
<span class="shipmentLineTitle">Delivery details: <b>your delivery will arrive on 08/10/2020 (1 delivery)</b></span>
I would suggest to user moment.js a very good date library to manipulate dates. It has lot of function to add/substract dates, hours, days etc.
There is https://www.npmjs.com/package/moment-business-days which servers exactly what you need
Here is my code so far. I am not sure how to accomplish a max date other than setting that in the input tag itself. I want it to be dynamic so whatever the current date is, the calendar only allows a selection of up to one year.
<input type="date" id="txtDate" />
$(function(){
var dtToday = new Date();
var month = dtToday.getMonth() + 1;
var day = dtToday.getDate();
var year = dtToday.getFullYear();
if(month < 10)
month = '0' + month.toString();
if(day < 10)
day = '0' + day.toString();
var maxDate = dtToday + 365;
alert(maxDate);
$('#txtDate').attr('max', maxDate);
});
example: today is 10/1/2019 it should be allowed to only select dated from 10/1/2019-10/1/2020 tomorrow a user should be allowed to only select from 10/2/2019-10/2/2020
link to fiddle
Setting the min and max values for a date input based on today's date can be done when the page loads:
// Formt date as YYYY-MM-DD
function formatISOLocal(d) {
let z = n => ('0' + n).slice(-2);
return d.getFullYear()+'-'+z(d.getMonth()+1) + '-' + z(d.getDate());
}
window.onload = function() {
let inp = document.querySelector('#i0');
let d = new Date();
inp.min = formatISOLocal(d);
inp.defaultValue = inp.min;
d.setFullYear(d.getFullYear() + 1);
inp.max = formatISOLocal(d);
// Debug
console.log(inp.outerHTML);
}
<input type="date" id="i0">
If the user agent doesn't support input type date, this will still set the min/max/default values, but you'll have to handle out of range values yourself.
Just add a year to the current date
var dtToday = new Date();
dtToday.setYear(dtToday.getYear() + 1);
$(function(){
var dtToday = new Date();
dtToday.setFullYear(dtToday.getFullYear() + 1)
let formatted_date = dtToday.getFullYear() + "-" + (dtToday.getMonth() + 1) + "-" + dtToday.getDate()
alert(formatted_date);
$('#txtDate').attr('max', formatted_date);
});
You can't add to a date object like that; you need to first get it as a timestamp. You can do that by using Date.now() or, if you need the Date object, dtToday.getTime().
That gives you a timestamp in milliseconds, so you also need to convert 365 days into milliseconds; meaning you want to add 365 * 24 * 60 * 60 * 1000 to it, not just 365.
I am very new to script and checked many answers but could not find the complete answer.
In a form, I have a start date, number of months and end date - I want to display the end date when the start date is entered - I have created this script but I must be missing something.
Here's my code:
[script type="text/javascript" src=Datejs][/js]
[script type="text/javascript" ]
window.onload = function() {
var startdateEl = document.getElementById("customFields_cf_232");
var leasetermEl = document.getElementById("customFields_cf_34");
var enddateEl = document.getElementById("customFields_cf_38");
function CalculateDate {
var enddateEl=leasetermEl.months().startdateEl;
}
var enddateEl.onblur = CalculateDate;
};
[/script]
I made this. It listens to your keystrokes live. http://jsfiddle.net/4t54J/
<input name="startDate" type="text" value="MM-DD-YYYY" />
<input name="endDate" type="text" />
var SECOND = 1000;
var MINUTE = SECOND * 60;
var HOUR = MINUTE * 60;
var DAY = HOUR * 24;
var YEAR = DAY * 365.25;
var startDateInput = 'input[name="startDate"]';
var endDateInput = 'input[name="endDate"]';
$(startDateInput).live('keypress', function (e) {
var startDate = $(startDateInput).val();
var endDate = setEndDate(startDate);
$(endDateInput).val(endDate);
});
function setEndDate(startDate) {
var date = new Date();
var parts = startDate.split('-');
if (date != '' && parts.length > 2) {
// year, month (0-based), day
date.setFullYear(parts[2], parts[0] - 1, parts[1]);
date.setTime(date.getTime() + YEAR);
var mm = date.getMonth() + 1;
mm = (mm < 10 ? '0' : '') + mm.toString();
var dd = date.getDate();
var yyyy = date.getFullYear();
return mm + "-" + dd + "-" + yyyy;
} else {
return '';
}
}
So I just have posted a question about this code (which was answered):
$(document).ready(Main);
function Main() {
ConfigDate();
}
function ConfigDate() {
var currentTime = new Date();
var dayofWeek = currentTime.getDay();
var daysSinceThursday = (dayofWeek + 3) % 7
var lastThursday = new Date(currentTime.getDate() - daysSinceThursday);
var dd = lastThursday.getDate();
var mm = lastThursday.getMonth() + 1;
var yyyy = lastThursday.getFullYear();
$("#last_thursday").text(yyyy + " / " + mm + " / " + dd);
}
The problem now is that the date that appears in my cell is 1969 / 12 / 31 (which isn't even a thursday).
Did I do something wrong while calculating last thursday date?
This is because .getDate() returns the day of the month. So you are building your date based on a serial number of something less than 30, which won't even set your seconds above 1.
Use .setDate() instead of building a new date:
date.setDate(date.getDate() - daysSinceThursday);
.setDate() will modify your existing date object, it doesn't return a new date.
You're trying to set a Date based only on the day of the month of the last Thursday. Try something like this:
var daysSinceThursday = (dayofWeek + 3) % 7;
var lastThursday = new Date(currentTime.getTime());
lastThursday.setDate(currentTime.getDate() - daysSinceThursday);
var dd = lastThursday.getDate();
var mm = lastThursday.getMonth() + 1;
var yyyy = lastThursday.getFullYear();
http://jsfiddle.net/rAuRF/3/
I want to compare the user's birthday against today's date and get the number of days in between. The birthday they enter will be in the form of 12/02/1987 in an input box of type text
In my JS file I have code that looks like this:
function validateDOB(element) {
var valid = false;
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //do that January is NOT represented by 0!
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
var today = mm + '/' + dd + '/' + yyyy;
alert(today);
if (element.value != today) {
var days = 0;
var difference = 0;
Christmas = new Date("December 25, 2011");
today = new Date();
difference = today - Christmas
days = Math.round(difference / (1000 * 60 * 60 * 24)-1);
alert(days);
valid = true;
}
Instead of using "Christmas" I want to compare element.value... how do I do this?
When I put difference = today - element.value it won't show me the difference. The alert box comes up as NaN.
I wrote a lightweight date library called Moment.js to handle stuff like this.
var birthday = moment('12/02/1987', 'MM-DD-YYYY');
var inputDate = moment(element.value, 'MM-DD-YYYY');
var diff = birthday.diff(inputDate, 'days');
http://momentjs.com/docs/#/displaying/difference/
You'll need to first parse element.value as a date:
difference = today - new Date(element.value);
http://jsfiddle.net/gilly3/3DKfy/