Date function in JS, comparing with a set date not working - javascript

I have to pretty much validate and check if the user is underage in ASP. So anyone under the age of 01/07/1998 is underage. I have 3 dropdown lists to select date, month and year. Im using JS. I try using concat and split but they dont work. Can anyone help with this?
function ValidateDate() {
var dDay = document.getElementById('DateList');
var dMonth = document.getElementById('MonthList');
var dYear = document.getElementById('YearList');
var day = dDay.selectedIndex;
var month = dMonth.selectedIndex;
var year = dYear.selectedIndex;
var firstValue = year + month + day;
var setyear = "1998";
var setmonth = "06";
var setdate = "01";
var secondValue = setyear + setmonth + setdate;
var firstDate = new Date();
firstDate.setFullYear(firstValue[0], (firstValue[1] - 1), firstValue[2]);
var secondDate = new Date();
secondDate.setFullYear(secondValue[0], (secondValue[1] - 1), secondValue[2]);
if (firstDate > secondDate) {
alert("Pass");
}
else {
alert("Fail");
}
}
<asp:CustomValidator ID="CustomValidatorDate" runat="server"
ErrorMessage=" You are underage" CssClass="error" Display="Dynamic" ClientValidationFunction="ValidateDate" ></asp:CustomValidator>

First of all your day, month and year variables are reading the index of the drop-downs and not their values.
For instance, you need to use:
var day = dDay.value,
month = dMonth.value,
year = dYear.value;
And then create date object as
var firstDate = new Date(year, month, day);
-Dipen

Related

days left until user's bday

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');

How to change format to standard time JavaScript

I have a date string in JavaScript which is arranged in a particular manner. How do I rearrange this in order to fit standard time?
let date = "2020-06-01T00:00:00Z"
How do I rearrange the date variable in order to match the format MM/DD, YYYY ?
Change your code to as follows:
let date = "2020-06-01T00:00:00Z";
date = new Date(date);
var dd = date.getDate();
var mm = date.getMonth()+1;
var yyyy = date.getFullYear();
if(dd<10){dd='0'+dd}
if(mm<10){mm='0'+mm};
console.log(mm+'/'+dd+', '+yyyy)
i don't real know this is possible but i found the function you can use instead
function GetFormattedDate() {
var todayTime = new Date();
var month = todayTime.getMonth() + 1;
var day = todayTime.getDate();
var year = todayTime.getFullYear();
return month + "/" + day + "/" + year;
}
console.log(GetFormattedDate());
so you can add more in the function or edit what the function will return as a format according to your will

Primefaces Calendar setDate not working properly

I'm facing an issue when trying to set the date and time of Calendar in primefaces 6.1 using javascript. I used the following code and at first, it was working but suddenly it stopped working. Now I can't figure out how to fix this thing. Sometimes it changes the date part but not the time part.
var recievedDateValue = PF('recievedDate').getDate();
PF('collectedDate').setDate(recievedDateValue);
XHTML Part:
<p:calendar id="caseCollectedDate" widgetVar="collectedDate" tabindex="50" value="#{caseController.selectedCase.caseCollectedDate}"
converter="DateConverter"
converterMessage="Please enter valid date time format" pattern="MM/dd/yy HH:mm" maxdate="#{viewUtilityBean.currentDate}"
timeControlType="slider" onfocus="getFocusElementId()" onchange="validateDate('collectedDate')">
<p:remoteCommand name="validateCollectedDateFromServer" update="#this"/>
</p:calendar>
DateConverter (getAsObject method):
if (!value.contains(":")) {
date1 = new SimpleDateFormat("MM/dd/yy").parse(value);
value = new SimpleDateFormat("MM/dd/yy HH:mm").format(date1.getTime());
date1 = new SimpleDateFormat("MM/dd/yy HH:mm").parse(value);
} else {
date1 = new SimpleDateFormat("MM/dd/yy HH:mm").parse(value);
}
I tried multiple ways to somehow work this but it is not working. Though setdate function calls the onchange event but the date doesn't change.
I overrode the setDate function of the primefaces calendar widget to the following.
The following are the snippets I tried.
setDate : function(a) {
var month = a.getMonth();
var date = a.getDate();
var year = a.getFullYear();
var hour = a.getHours();
var min = a.getMinutes();
this.jqEl.datetimepicker("setDate",new Date(month,date,year,hour,min))
}
setDate : function(a) {
var month = a.getMonth();
var date = a.getDate();
var year = a.getFullYear();
var hour = a.getHours();
var min = a.getMinutes();
this.jqEl.datetimepicker({
userCurrent: false,
format: 'MM-dd-yy HH:mm',
date: new Date(month,date,year,hour,min)
})
}
setDate : function(a) {
var month = a.getMonth();
var date = a.getDate();
var year = a.getFullYear();
var hour = a.getHours();
var min = a.getMinutes();
this.jqEl.datetimepicker({
date: new Date(month,date,year,hour,min)
})
}
setDate : function(a) {
var month = a.getMonth();
var date = a.getDate();
var year = a.getFullYear();
var onlyDate = month+"/"+date+"/"+year;
var hour = a.getHours();
var min = a.getMinutes();
this.jqEl.datetimepicker({
date: onlyDate,
hour: hour,
minute: min
})
}
setDate : function(a) {
$('#clientTabs\\:j_idt1125\\:caseCollectedDate_input').data("DateTimePicker").date(a);
}
Calendar looks like this.

How to get days between date range by using javascript or jquery

In a form, I define a start date, an end date, and weekdays
Example:
Start date: 2017-02-07
End date: 2017-03-07
Weekdays: Monday and Thursday
Now I want to get all Mondays and Thursdays between start date and end date by using Javascript or jQuery.
Who can help me?
Thanks...
Simple code. Codepen
var startDate = new Date('2017-02-07');
var endDate = new Date('2017-02-17');
var monday = [];
var thursday = [];
for (var d = new Date(startDate); d <= new Date(endDate); d.setDate(d.getDate() + 1)) {
if(d.getDay()==1)
monday.push(d);
else if(d.getDay()==4)
thursday.push(d);
}
You can parse date and iterate over increment 1 day and getDay to map with sun(0) to sat(6)
var startDate = new Date("2017-02-07");
var endDate = new Date("2017-03-07");
var totalMon = [];
var totalThu = [];
for (var i = startDate; i <= endDate; ){
if (i.getDay() == 1){
totalMon.push(i.getFullYear() + "-" + (i.getMonth()+1) + "-" + i.getDate());
}
if (i.getDay() == 4){
totalThu.push(i.getFullYear() + "-" + (i.getMonth()+1) + "-" + i.getDate());
}
i.setTime(i.getTime() + 1000*60*60*24);
}
console.log(totalMon.length ,totalMon);
console.log(totalThu.length ,totalThu);
Below code finds number of Mondays. You can modify it to calculate any day. It basically finds the difference of days in two dates. Divide it by 7 (this is the number of times everyday will come). Now for pending days loop through the dates and check if a desired day comes in this loop.
var startDate = new Date(2017, 02, 07);
var endDate = new Date(2017, 03, 07);
var dayDiff = Math.round((endDate-startDate)/(1000*60*60*24));
var numberOfMondays = Math.floor(dayDiff/7);
var remainingDays = dayDiff%7;
for(i=0;i<remainingDays;i++)
{
var dateObj = new Date();
dateObj.setDate(endDate.getDate() - i);
if(dateObj.getDay() == 2)
numberOfMondays=numberOfMondays+1;
}
alert(numberOfMondays);
PS : the other two answer are looping through all the dates. I will not suggest this. In code above the number of iterations in loop will never exceed 6 irrespective of the difference in dates.

How can i convert seconds into date format in Javascript

The code is as below my Start_DateVal has the selected date and from the datepicker .And i am trying to alert the date which is 8 months ahead from the selected date (Start_DateVal).
function ChangeEndDate()
{
var Start_DateVal = document.getElementById("Start_Date").value;
if(Start_DateVal!='')
{
var arr=Start_DateVal.split("-");
var day= arr[0];
var month= arr[1];
var year= arr[2];
var d = new Date(year, month, day);
var InSeconds=d.setMonth(d.getMonth() + 8);
alert(InSeconds); //Here i wanted to display in date format instead of seconds.
}
}
Problem Statement: i am getting the alert in Seconds (InSeconds) Variable .But how do i convert Seconds into DD-MM-YYYY Date Format.Please Help me Thank you.
var d = new Date(2017, 01, 12);
var date = d.getDate();
var month = d.getMonth()+1;
var year = d.getFullYear();
if(date<10){
date='0'+date;
}
if(month<10){
month='0'+month;
}
alert(date + '-' + month + '-' + year)

Categories

Resources