How to add certain number of months to a date in javascript? - javascript

I'm getting the number of months value from another field and this has to be added to the date present in another field. Below is the code:
HTML:
<template>
<lightning-card>
<label for="signatureDate">Signature Date:</label> <br>
<lightning-input type="date" id="signatureDate" min={todaysDate} style="width: 30em ;">
</lightning-input>
<br><br>
<label for="signatureDate">Prescription Duration (in months):</label> <br>
<lightning-input type="String" id="prescriptionDuration" onchange={calculateExpiryDate} style="width: 30em ;">
</lightning-input>
<br><br>
<label for="expiryDate">Expiry Date:</label> <br>
<lightning-input type="String" id="expiryDate" readonly value={expiryDate} style="width: 30em ;">
</lightning-input>
</lightning-card>
</template>
JS:
#api Prescriber;
#api signatureDate;
#api prescriptionDuration;
#track expiryDate='';
calculateExpiryDate( event ) {
this.signatureDate = event.target.value;
this.prescriptionDuration = event.target.value; //this field takes in some integer to denote number of months
console.log(this.signatureDate);
let date = new Date(this.signatureDate);
let expDate = new Date();
expDate.setDate(date.getDate());
expDate.setMonth(date.getMonth()+parseInt(this.prescriptionDuration));//Adding number of months from other field
expDate.setFullYear(date.getFullYear()+1);
this.expiryDate=expDate.toDateString();
}
}
I tried adding the number of months while setting the date but I get incorrect output.
Input: Feb 15,2023
Duration in months to add: 1
Expected Output: March 15,2023
Actual Output: Feb 01, 2002
I'm not sure how the output is going back in time!

Related

how to disable past time from current time soo that user cant select the time which is over only select the time which is in future of type="time"

<div class="date-time-para">
<div class="box-date">
<label class="font-weight-bold"> Select Date {{notificationDetails.scheduled_date}}</label>
<!-- <input type="date" formControlName="notificationDate" placeholder="Select Date" class="input-sample" placeholder="Select Date" [(ngModel)]="notificationDetails.scheduled_date"> -->
<input type="date" formControlName="notificationDate" [ngModel]="notificationDetails.scheduled_date | date:'yyyy-MM-dd'" [min]="currentDate" />
</div>
<div class="box-date">
<label class="font-weight-bold">Select Time</label>
<!-- <input type="tśme" formControlName="notificationTime" placeholder="Select Date" class="input-sample" placeholder="Select Date" [(ngModel)]="notificationDetails.scheduled_time"> -->
<input type="time" formControlName="notificationTime" [ngModel]="notificationDetails.scheduled_time | date:'HH:MM'" [min]="currentDate " />
</div>
</div>
i want that in input type = "time" user can't able to select time which is passed when time popup opens
and i have defined [min] = "currentTime" which is in .ts file in angular giving hour and minutes using date = new Date() in javascript

Bootstrap Date Picker Validation

Hey guys I am working on a project that requires validation of the date picker to check whether the end date is greater than or equal to the start date! Can anyone help me with how to write jquery for it so that I can disable the dates based on the user's date selection restricting him/her to choose the dates within the starting and ending range entered by the user?
The code looks like this:
<div class="mb-4">
<label for="startdate" class="form-label">StartDate</label>
<input type="date" class="form-control" id="startdate" name="startdate" />
</div>
<div class="mb-4">
<label for="enddate" class="form-label">End Date</label>
<input type="date" class="form-control" id="enddate" name="enddate" />
</div>
I'm not sure how to disable inside picker dates that are higher than the startDate, but like this you can do a validation
var startDate = new Date($('#startdate').val());
var endDate = new Date($('#enddate').val());
if (startDate < endDate){
// Do something
}

How to change value inside textfield HTML

How can I change the value inside my Revenue textfield by subtracting the Cost of Good value from the Sales Price value? I have attached an image of what it looks like currently, but I want to change whats displayed inside my Revenue field after I edit the previous 2 text fields. I have also attached my code.
See attached image
<div class="product-section">
<h3>
<b>{{ product.productLabel }}</b>
</h3>
<label for="sales-price">Sales Price: </label>
<br>
<input
type="text"
[(ngModel)]="product.salesPrice"
name="sales-label"
placeholder="Enter Sales Price"
/>
<p></p>
<label for="cogs">Cost of Good: </label>
<br>
<input
type="text"
[(ngModel)]="product.cogs"
name="cogs-label"
placeholder="Enter Cogs"
/>
<p></p>
<label for="rev">Revenue: </label>
<br>
<input
type="text"
[(ngModel)]="product.rev"
name="rev-label"
readonly
/>
</div>
Add (keyup)="getRev()" to your Sales Price and Cost of Goods inputs.
<div class="product-section">
<h3>
<b>{{ product.productLabel }}</b>
</h3>
<label for="sales-price">Sales Price: </label>
<br>
<input
type="text"
[(ngModel)]="product.salesPrice"
(keyup)="getRev()"
name="sales-label"
placeholder="Enter Sales Price"
/>
<p></p>
<label for="cogs">Cost of Good: </label>
<br>
<input
type="text"
[(ngModel)]="product.cogs"
(keyup)="getRev()"
name="cogs-label"
placeholder="Enter Cogs"
/>
<p></p>
<label for="rev">Revenue: </label>
<br>
<input
type="text"
[(ngModel)]="product.rev"
name="rev-label"
readonly
/>
</div>
Then add a function to your component's typescript file to handle the revenue calculation.
getRev() {
this.product.rev = this.product.cogs - this.product.salesPrice;
}
Can you post the body of getRev()? And, take the quotes away from getRev() so that it calls the function instead of sets the value as the literal string 'getRev()'
Edit:
Is there a way to just subtract the cogs value from my sales value?
Yes, you could use an onchange handler. Here is an example, assuming you set the ID of the three elements as 'cogs', 'sales', and 'revs':
const cogs = document.getElementById('cogs');
const sales = document.getElementById('sales');
const revs = document.getElementById('revs');
cogs.addEventListener('input', (event) => {
const salesNumber = Number(sales.value);
const cogsNumber = Number(cogs.value);
const difference = salesNumber - cogsNumber;
revs.value = difference;
});

Input type date - date range same for every year

I have a contact form with 2 inputs of type date. I've set min and max date but they are set for the current year only. Is there a way to put the selected date range for every year?
https://jsfiddle.net/3akf49jr/
HTML
<form>
<label for="">Arrival date</label>
<input type="date" name="" min="2019-09-01" max="2019-10-01" id="minDate">
<label for="">Departure date</label>
<input type="date" name="" max="2019-10-01" id="maxDate">
</form>
JS
document.getElementById('minDate').onchange = function () {
document.getElementById('maxDate').setAttribute('min', this.value);
};
I also have a script that restricts dates in the second field based on a selected date in the first date field. I would like that functionality to remain.

extract year from date and calculate datedifference

I am relative new in coding and recently i have to do some date manipulations with data entered in a form. I searched a lot and I haven't found the solution that works for me.
Here is the issue:
The user enters following data in datetime-local fields in HTML:
1) Year of entering College (date 1)
2) Year of graduation (date 2)
3) Birthday (date 3)
I need a JQuery or a JavaScript script that uses this dates and output following:
1) Year of admitting, based on the admittion date (I know there is a getFullYear function, but I couldn't use it right...) >>> result1
2) Age at graduation (date difference between Birthdate and date of Graduation. >>> result2
I tried with adding datepicker but somehow I got really awful looking calendar which was displayed over the boxes. I couldn't install datetimepicker...
Thank you in advance. Your help is appreciated.
Here is my HTML code.
<input id="date1" type="datetime-local"/>
<label for="date1">admittion in Colleage</label>
<br />
<input id="result1" type="text" readonly="true" name="year" placeholder="=(getFullYear from date1)"/>
<label for="result1">year</label>
<br />
<input id="date2" type="datetime-local" />
<label for="date2">graduation</label>
<br />
<input id="date3" type="date" name="born" />
<label for="date3">born</label>
<br />
<input id="result2" type=“text” name="age" readonly="true" placeholder="=DATEDIF(Date3, Date2, Year)"/></textarea>
<label for="result2">age</label>
<br />
You didn't include the js code which is more important for this question. I'll include a couple functions that should help.
To find a year from a date, I use the following function
function getYearFromDate(date){
const yearFromDate = new Date();
yearFromDate.setTime(date.getTime());
yearFromDate.setFullYear(date.getFullYear() + 1);
return yearFromDate;
}
console.log(getYearFromDate(new Date()));
And the graduation age copied mostly from Calculate age given the birth date in the format YYYYMMDD
function getYearsBetween(oldDate, newDate) {
var age = newDate.getFullYear() - oldDate.getFullYear();
var m = newDate.getMonth() - oldDate.getMonth();
if (m < 0 || (m === 0 && newDate.getDate() < oldDate.getDate())) {
age--;
}
return age;
}
Including moment.js is also an option, but it's a large library I like to avoid if I can.
EDIT I thought you wanted year + 1 day. Getting the full year from the date is even easier.
const date = new Date();
console.log(date.getFullYear());
Edit: All together now
function updateGradYear(event) {
console.log(event.target.value);
let date = new Date(event.target.value);
document.querySelector('#result1').value = date.getFullYear();
}
function updateAge() {
let gradDate = new Date(document.querySelector('#date2').value);
console.log(document.querySelector('#date3').value);
let birthdate = new Date(document.querySelector('#date3').value);
document.querySelector('#result2').value = gradDate.getFullYear() - birthdate.getFullYear();
}
// set some default values
let today = new Date();
document.querySelector('#date1').value = today.toISOString().split('.')[0];
document.querySelector('#result1').value = today.getFullYear();
document.querySelector('#date2').value = today.toISOString().split('.')[0];
let birthdate = new Date(today.getTime);
birthdate.setFullYear(1984);
console.log(birthdate.toISOString().slice(0, 10).replace(/\//g, "-"));
document.querySelector('#date3').value = birthdate.toISOString().slice(0, 10).replace(/\//g, "-");
updateAge();
<input id="date1" type="datetime-local" onchange="updateGradYear(event)" />
<label for="date1">admittion in Colleage</label>
<br />
<input id="result1" type="number" readonly="true" name="year" placeholder="=(getFullYear from date1)" />
<label for="result1">year</label>
<br />
<input id="date2" type="datetime-local" onchange="updateAge()" />
<label for="date2">graduation</label>
<br />
<input id="date3" type="date" name="born" onchange="updateAge()" />
<label for="date3">born</label>
<br />
<input id="result2" type=“text” name="age" readonly="true" placeholder="=DATEDIF(Date3, Date2, Year)" /></textarea>
<label for="result2">age</label>
<br />
Let me know how this works for you! And as i said please enter all the fields while running this code!
$('#date1, #date2').on('blur',function(){
var dc = document.querySelector('input[id="date1"]');
var date = new Date(dc.value);
var collegeadmission = date.getFullYear();
$('#result1').val(date.getFullYear());
dc = document.querySelector('input[id="date2"]');
date = new Date(dc.value);
var collegegrad = date.getFullYear();
if(! isNaN(collegegrad))
$('#result2').val(collegegrad - collegeadmission);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="date1" type="datetime-local"/>
<label for="date1">admittion in Colleage</label>
<br />
<input id="result1" type="text" readonly="true" name="year" placeholder="=(getFullYear from date1)"/>
<label for="result1">year</label>
<br />
<input id="date2" type="datetime-local" />
<label for="date2">graduation</label>
<br />
<input id="date3" type="date" name="born" />
<label for="date3">born</label>
<br />
<input id="result2" type=“text” name="age" readonly="true" placeholder="=DATEDIF(Date3, Date2, Year)"/></textarea>
<label for="result2">age</label>
<br />
check out this url:http://jsbin.com/vebiwogipu/edit?html,js,output
Make sure u fill all the dates and time properly as you discussed in your html.
Similarly you can attach the output on click or change event.
and aso you can leverage getMonth() and getDay() in the code to get desired output.
Take a look at the label and may be alert, when you click the button, it shows year out of your first date field. As i said you need to add the logic for rest.
let me know if it makes sense, if not please add more information to make me understand!

Categories

Resources