Javascript simple code error - javascript

Can't seem to find the problem. Every time I run it I get NaN for ageDale, been looking at it for a while now, its probably simple but I appreciate the help!
<p>Enter names in the fields, then click "Submit" to submit the form:</p>
<form name="form">
<input type="text" id="birthDate">
Current Date
<input type="text" id="currentDate">
<a id="Submit_Button" onclick="test();" href="javascript:void(0);" title="Submit">Submit</a>
</form>
<script>
function test() {
var birthDate = document.getElementById("birthDate");
var currentDate = document.getElementById("currentDate");
var ageDate = (birthDate.value - currentDate.value);
if(ageDate.value < 1) {
(ageDale = ageDate.value * -1)
}
else {
(ageDale = ageDate.value * 1)
}
alert(ageDale)
}
</script>
Also, is it necessary for me to have that else statement? or is there another way to set up this so its not needed?

This
ageDate.value
should be
ageDate
only. It's a variable and already contains only the difference from
birthDate.value - currentDate.value
if(ageDate.value < 1) {
// ^ here
(ageDale = ageDate.value * -1)
} //^ here
else {
(ageDale = ageDate.value * 1)
// ^ and here
You only need to fetch the value when getting data from, for example, input fields.
Also (depending on how you input them) it might be a problem to calculate dates. For debugging purposes you should
console.log()
your variable values, that way you will find out quickly where the error is.
A good place for a console.log() in your code would be, for example after this block:
var birthDate = document.getElementById("birthDate");
var currentDate = document.getElementById("currentDate");
var ageDate = (birthDate.value - currentDate.value);
console.log(ageDate);
SIDENOTE:
You might want to take a look at moment.js, which will help you with date calculations. For example, you can get differences between dates with moment.js like this:
var a = moment([2014, 12, 05]);
var b = moment([2014, 12, 06]);
a.diff(b, 'days') // 1

Try this:
var btn = document.getElementById("Submit_Button");
btn.onclick = function test() {
var birthDate = parseInt(document.getElementById("birthDate").value);
var currentDate = parseInt(document.getElementById("currentDate").value);
var ageDate = (birthDate - currentDate);
if(ageDate < 1) {
(ageDate = ageDate * -1)
}
else {
(ageDate = ageDate * 1)
}
alert(ageDate)
}

As baao said, you have spelling errors. After correcting those, you want to consider what your input is going to be, and make sure you are checking that the input is valid.
For example, if I type "September 10th" for my birthday and "December 10th" for the current date, your function will try and subtract two strings which is not valid. If you're going to use a custom input field for the date, you need to be sure its in a consistent and parseable format.
I'd recommend asking for just their birthday in a specific format and parsing it from there, since we can use Javascript to get the current date easily. For example, mm-dd-yy. We may re-write it as:
function test() {
//lets get the date, in the format 'mm-dd-yy'. You'd want to do error checking at some point if you're serious about it
var dateInput = document.getElementById("birthDate").value;
//get each individal date type by splitting them at the -, giving ['dd', 'mm', 'yy']
var dateSplit = dateInput.split('-');
//create a Javascript date object with the date we got
var birthDate = new Date(dateSplit[2], dateSplit[0], dateSplit[1]);
//create another with the current date and time
var currentDate = new Date();
// find the difference in milliseconds
var dateDifference = Math.abs(birthDate.getTime() - currentDate.getTime());
// convert to years
var age = dateDifference / (1000 * 3600 * 24 * 365);
alert(age);
}
<p>Enter names in the fields, then click "Submit" to submit the form:</p>
<form name="form">
Birth Date (dd-mm-yy):
<br>
<input type="text" id="birthDate">
<br>
<a id="Submit_Button" onclick="test();" href="javascript:void(0);" title="Submit">Submit</a>
</form>

just modify this code
var birthDate = document.getElementById("birthDate");
var currentDate = document.getElementById("currentDate");
var ageDate = (birthDate.value - currentDate.value);
if(ageDate.value < 1) {
(ageDale = ageDate.value * -1)
}
else {
(ageDale = ageDate.value * 1)
}
with this
var vbirthdate = new Date(document.getElementById("birthDate").value);
var vcurrentdate = new Date(document.getElementById("currentDate").value);
var ageDate = Math.floor((vbirthdate-vcurrentdate)/(1000*60*60*24));
if(ageDate < 1) {
(ageDate = ageDate * -1)
} // no need to do something like this (ageDate *1) if it is already a positive number, just check if it's a negative then convert it to a positive number
you can try the code at http://jsfiddle.net/kapasaja/duco4cqa/5/
what you asking is similar to this post

Related

Date validation and relative delta between two dates in javascript

I have an interface where I receive a date in this format: Month/Year, ex: 11/2022.
I would like to verify that this is a valid date.
I use the datatables editor. The configuration (see below) of the field works well, but since the user can enter the date himself without going through the calendar, there is a risk that the date entered is incorrect. It doesn't work like an input mask. So i need to validate the date in the code.
{
type: "datetime",
label: "Date:",
name: "Date",
def: function () { return new Date(); },
format: 'MM/YYYY',
fieldInfo: 'Format: Month/Year (ex: 12/2022)',
keyInput: true
}
The date should not be accepted if the difference between this date and today's date is less than 3 months.
It means that, compared to today, all dates before July will have to be rejected.
Currently I can do this with the relativedelta method of the python dateutil module. But as the validation must be done on the client side, I would like to do this in javascript (which I know very little).
The example below shows how to do this. You should take advantage of the HTML 5 input types to validate your dates. You also need to calculate 3 months from now in myEpoch and then compare it to the date/time given
HTML:
<p>
Date & Time: <input id="foo" type="datetime-local" />
</p>
JavaScript:
var myEpoch = new Date();
myEpoch.setMonth(myEpoch.getMonth() + 3);
myEpoch = myEpoch.getTime();
var foo = document.getElementById("foo");
if (foo.value < myEpoch) {
//show a message saying this date is invalid
}
Since user is entering date in MM/yyyy format, so i'm assuming that you take 1 as a date into account, i.e., if input is 03/2020, you would consider it as: 01/03/2020. Right? If
so, then you can do the following to validate this date:-
function isValidDate(inputDate) {
// Unfortunately JS doesn't have any in-built function to validate date in MM/yyyy format. Hence regex comes to the rescue
var regex = /^([0-9]{1,2})\/([0-9]{4,4})$/;
var matches = regex.exec(inputDate);
if (!matches || matches.length != 3) {
throw new Error('Please provide date in MM/yyyy format');
}
var inputMonth = matches[1]; // Return month from input date
var inputYear = matches[2]; // Return year from input date
var finalDate = inputMonth+ '/01/' + inputYear;
// Check if entered date is valid or not
var parsedDate = Date.parse(finalDate);
if (isNaN(parsedDate)) {
throw new Error('Unable to parse date.');
}
// Check if it is less than 3 months or not.
var isValid = !isLessThan3Months(new Date(finalDate), new Date());
return isValid;
}
function isLessThan3Months(dateToCompare, currentDate) {
var diffYears = currentDate.getFullYear() - dateToCompare.getFullYear();
var diffMonths = currentDate.getMonth() - dateToCompare.getMonth();
var diffDays = currentDate.getDate() - dateToCompare.getDate();
var months = diffYears * 12 + diffMonths;
if (diffDays > 0) {
months += '.' + diffDays;
} else if (diffDays < 0) {
months--;
months +=
'.' +
(new Date(currentDate.getFullYear(), currentDate.getMonth(), 0).getDate() + diffDays);
}
return months < 3;
}
isValidDate('03/2020');
So now, by calling isValidDate with user's input date in MM/yyyy format, you should be able to check if it is valid or not.
For this, you won't need to use any third party javascript library. Just plain javascript is enough.
You should probably use Moment.js, because working with the raw Date object is fiddly.
If you would rather use plain JavaScript, then the following might be of use:
const moreThan3MonthsHence = ({ utcYear, utcMonth },
now = new Date,
target = new Date(Date.UTC(utcYear, utcMonth)),
threeMonthsHence = addMonths(new Date(now.valueOf()), 3)) =>
(target > threeMonthsHence)
const validate = (str,
[utcMonth, utcYear] = str.split('/'),
date = new Date(Date.UTC(+utcYear, (+utcMonth)-1))) =>
moreThan3MonthsHence({ utcYear: date.getUTCFullYear(), utcMonth: date.getUTCMonth() })
const addMonths = (date, months, d = date.getDate()) => {
date.setMonth(date.getMonth() + +months);
// If rolled over to next month, set to last day of previous month
if (date.getDate() != d) {
date.setDate(0);
}
return date;
}
// Note: input is one-based months
console.log(validate('07/2020')) // true
console.log(validate('06/2020')) // false
console.log(validate('12/2019')) // false
Notes
now is internally represented as the milliseconds since the Unix epoch. Note this includes the current time of day.
target is the milliseconds since the Unix epoch of midnight on the supplied UTC date.
threeMonthsHence is the milliseconds since the Unix epoch of now (including time of day), plus three months.
validate parses the input string.
addMonths is necessary because the built-in function can roll-over into a new month with unexpected behavior.
Finally to solve my problem I mixed the solutions proposed by #Sumit Parakh and #ControlAltDel.
function isValidDate(inputDate) {
var regex = /^([0-9]{1,2})\/([0-9]{4,4})$/;
var matches = regex.exec(inputDate);
var parsedDate = 0;
if (!matches || matches.length != 3) {
throw new Error('Please provide date in MM/yyyy format');
}
else {
var inputMonth = matches[1]; // Return month from input date
var inputYear = matches[2]; // Return year from input date
var finalDate = inputMonth+ '/01/' + inputYear;
// Check if entered date is valid or not
var parsedDate = Date.parse(finalDate);
if (isNaN(parsedDate)) {
parsedDate = 0;
//throw new Error('Unable to parse date.');
}
return parsedDate;
}
var myEpoch = new Date();
myEpoch.setMonth(myEpoch.getMonth() + 3);
myEpoch = myEpoch.getTime();
finalDate = isValidDate(date_peremption.val());
if (finalDate == 0){
date_received.error("This date is invalid");
}
else if(finalDate < myEpoch) {
date_received.error("The date must be more than three months last");
}
It's not very elegant, but it works. Thanks everyone

Php date difference through javascript

Can anyone tell me that how make the validation for the date input type in a form to count the difference between current date and the provided date to measure whether the difference is greater than 18 years or not.
Note: the JavaScript can be called on submit button and show result in alert box.
You can simply subtract them to get difference in milliseconds.
var age = Math.floor((new Date() - new Date(dateString)) / (1000*60*60*24*365.25))
You can use valueAsDate to get the Date corresponding to the submitted value and confront that with "now" date.
HTML
<form id="myForm">
<input type="date" name="dateInput" id="dateInput" value="2013-08-01" />
<input type="submit">
</form>
JS
$(function() {
$('#myForm').submit(function() {
var _submittedDate = document.getElementById('dateInput').valueAsDate;
var _now = new Date();
var _milliPerYear =1000*60*60*24*365.26;
var _dateDifference = (_now - _submittedDate);
if ((_dateDifference/_milliPerYear) > 18) {
alert("VALID");
} else {
alert("Invalid");
}
return false; //Avoid form submission for testing
});
});
Here's a working example: http://jsfiddle.net/LinoLinux/rtvbysxs/1/
You could use something like this. But beware that this depends on the date string format of Javascript (Date constructor or Date.parse() : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date ). You should add an additional check to be sure you have a valid date string that the Date object will be able to parse.
<script>
function testDate() {
var dateString = document.getElementById('datefield').value
var currentDate = new Date();
var providedDate = new Date(dateString);
var diff = currentDate - providedDate;
var years = diff/1000/60/60/24/365;
if (years < 18) {
alert('Not old enough !');
return false
}
}
</script>
<form onsubmit="return testDate()">
<input type="date" id="datefield" />
<input type="submit" />
</form>
you probably should add an event handler for the submit of the form, and check the date in that handler. How to calculate the age is described here:
function getAge(dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
console.log('age: ' + getAge("2010/08/10"));
jsfiddle

Convert a String to a Single Date in Javascript

I have an input text that has a combination of date and time and display like this
04/01/2015 8:48PM
How can i convert this string to a date using the function new Date() in javascript? not output is shown
Here is what i've tried so far, i can only convert the date not the time.
HTML
<form name="frm1" >
<h3>Check in Date:</h3>
<input type="text" value="" class="datetimepicker_mask" name="dtp1" /><br><br>
<h3>Check out Date:</h3>
<input type="text" value="" class="datetimepicker_mask" name="dtp2" /><br><br>
<input type="button" onclick="computeDate()" value="Compute Difference" />
<br><b>No of days: </b>
<span id="date_difference"></span>
</form>
JAVSCRIPT
function computeDate() {
var dateTime1 = document.frm1.dtp1.value;
var dateTime2 = document.frm1.dtp2.value;
var startDate = new Date(dateTime1);
var endDate = new Date(dateTime2);
var timeDiff = Math.abs(endDate.getTime() - startDate.getTime());
if (timeDiff == 0) {
timeDiff = 1;
}
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
var total = parseFloat(diffDays) * parseFloat(roomRate);
document.getElementById("date_difference").innerHTML = diffDays;
document.getElementById("date_difference").style.visibility = "visible";
}
If the date format is always the same, create a convience function that converts the date to a Date object
function convert(date) {
var dateArr = date.split(/[\s\/\:]/);
if (dateArr[4].toLowerCase().indexOf('pm') != -1)
dateArr[3] = (+dateArr[3]) + 12;
dateArr[4] = dateArr[4].replace(/\D/g,'');
dateArr[0]--;
return new Date(dateArr[2], dateArr[0], dateArr[1], dateArr[3], dateArr[4]);
}
FIDDLE
Here is an answer that will both solve this and make development easier. This suggestion will require an extra library for addressing such issues as you are having here- time, but you'll likely find it beneficial when working with JavaScript dates in general. It already looks like you're writing manual date functions. Abstract them away with robust libraries for solving these same issues that have come up again and again. Using date.js, here is how easy this becomes
Date.parse('04/01/2015 8:48PM ')
JSFiddle Example
You can create the Date object after parsing the dateString
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
you can use the parseDate function as following
var testDate = "04/01/2015 8:48PM";
console.log(parseDate(testDate));
function parseDate(dateStr){
var dateTime = dateStr.split(/\/| |:|(?=[PA])/);
for(var i=0; i<5; i++){
dateTime[i] = parseInt(dateTime[i]);
}
if(dateTime[5] == "PM"){
dateTime[3] += 12;
}
return new Date(dateTime[2], dateTime[1], dateTime[0], dateTime[3], dateTime[4]);
}
Try it at JSFiddle

check if "current time" is between 2 times. But also check for nights as the day before

I have 2 times for example: 10:00 and 1:00 now i want to check if current time... is between these 2 times in javascript.
The problem is that the closing time in this case is a next day so its before the openingstime. How can i do this the proper way for some reason i can not get around this.
i hav efound that this could solve it:
var start = new Date(2012,6,20,13).getTime();
var now = new Date().getTime();
var end = new Date(2012,6,21,2).getTime();
if( (start < now ) && (now < end )) {
console.log("opened");
}
else {
console.log("closed");
}
but how can i do it with 2 string formats like 10:00 and 2:00 because i do not see a option to put a time alone
var d = new Date();
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
You could use a simple function like this to convert your time to a number of minutes since 0:00:
function getMinutes(str) {
var time = str.split(':');
return time[0]*60+time[1]*1;
}
And a similar function to get the current time into the same form in order to compare:
function getMinutesNow() {
var timeNow = new Date();
return timeNow.getHours()*60+timeNow.getMinutes();
}
Then convert both opening and closing time and, if it happens that closing time is before opening time, add 24 hours to it.
var now = getMinutesNow();
var start = getMinutes('10:00');
var end = getMinutes('2:00');
if (start > end) end += getMinutes('24:00');
if ((now > start) && (now < end)) { // your code here
This is the solution I've gotten to after a bit of fiddling. At the current time of 3:24 am, it outputs the correct information. changing the now array to be [13,00] also gave the correct result of 'closed' Give it a test run through to make sure it works correctly.
Edit
jQuery included solely because I am brain dead.
Edit#2
I noticed now (9pm my time) that my conversion wasn't working, it was saying 'closed', when it shouldn't have. So far, this works for any and all numbers I've put in it to test.
var start_time = [20,00]
var end_time = [12,00]
//We've got the two start times as an array of hours/minutes values.
var dateObj = new Date(); //I just feel dirty making multiple calls to new Date().etc
var now = [dateObj.getHours(),dateObj.getMinutes()]; //Gets the current Hours/Minutes
if(end_time[0] < start_time[0] && now[0] < start_time[0]){
start_time[0] -= 24; //This is something I came up with because I do a lot of math.
}else if(start_time[0] > end_time[0]){
end_time[0]+=24;
}
var el=$('#result');
var start_string = to_hms_string(start_time); //the start string converted to a string format. Made comparisons easier.
var end_string = to_hms_string(end_time); //See Above
var now_string = to_hms_string(now); //Above
console.log(start_string, now_string, end_string);
var status = (start_string < now_string && now_string < end_string) ? "Open" : "Closed";
el.html(status);
//Function to_hms_string stands for "hour-minute-second" string. First name that came up.
function to_hms_string(timearr){
var minutes = 60+timearr[1];
var hours = "";
if(Math.abs(timearr[0]) < 10){
hours = "0";
}
hours = (timearr[0]<0) ? "-"+hours+Math.abs(timearr[0]) : hours+timearr[0];
return hours+":"+minutes;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result">
PlaceHolder
</div>
You can do this, get current time. Then define you start time and end time based on the current time getting the year, month, date for tomorrow's date add 1 to the start's date see code below. Then you can compare the time the same fi condition you have. Good luck
var now = new Date();
var start = new Date(now.getFullYear(),now.getMonth(),now.getDate(),7).getTime();
var end = new Date(now.getFullYear(),now.getMonth(),now.getDate() + 1,2).getTime();
now = now.getTime();
if( now >= start && now < end) {
console.log("opened");
}
else {
console.log("closed");
}
***EDIT**
You can convert the current time to millis after you get the year, month and date. Then use your current if condition.
Jhecht This thing right here:
if(end_time[0] < start_time[0] && now[0] < start_time[0]){
start_time[0] -= 24;
}else if(start_time[0] > end_time[0]){
end_time[0]+=24;
}
it's brilliant. It works and this is the correct answer. Great job!

How to change a particular value when I select a date?

The requirement is I have two date fields:
One is effective date and date of birth. When I select the effective date on the page.
The age field should do the following calculation.
That is age would be Effective date - date of birth. the result should be set to the age field.
How to do in javascript or JQuery?
I'm using tapestry front end. So in the HTML page I want to do this setting of value to age field.
You need to convert your dates into milliseconds and subtract them, then calculate the age.
HTML
<input type="date" id="effective" />
<input type="date" id="born" />
jQuery
function getTime(date){
var dateArr = date.split('-');
return new Date(dateArr[0], dateArr[1], dateArr[2]).getTime();
}
function calcDate(date1,date2) {
var eff_date = getTime(date1);
var born_date = getTime(date2);
var diff = Math.floor(eff_date - born_date);
var day = 1000* 60 * 60 * 24;
var days = Math.floor(diff/day);
var months = Math.floor(days/31);
var years = Math.floor(months/12);
return years
}
$("input[type=date]").change(function(){
if($("#effective").val() != "" && $("#born").val() != ""){
var age = calcDate($("#effective").val(),$("#born").val())
alert(age);
}
});
Check out this Fiddle..

Categories

Resources