Calculating date field based on another date field - javascript

I need to create a form with 2 date fields.
User will enter first date field (start-date) and I need to calculate 4 weeks from start date in the second date field (one-month-expiry). Better still: is there a way to calculate 1 calendar month instead of weeks?
I've managed to get the second field to populate a date - but it's not correct.
This is JavaScript, which I don't really understand. I've managed to get this far just by googling.
<script type="text/javascript">
document.getElementById('one-month-expiry').value
= (new Date(document.getElementById('start-date').valueAsDate
+ (6.04e+8 * 4)))
.format("dd/MM/yyyy");
</script>
It keeps returning the same date (29/01/1970). So I've obviously managed to stuff something up.
Any ideas how to include the first date field as part of my calculation?

<script type="text/javascript">
let date = new Date(document.getElementById('start-date').valueAsDate);
date.setMonth(date.getMonth() + 1);
document.getElementById('one-month-expiry').value = date.format("dd/MM/yyyy");
</script>
Beware that this might have some issues with edge cases. For example, adding one month to 31st January will give you 31st February, which does not exist, causing the date to roll over to 2nd March instead.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Related

Javascript: Set date, show date +14 days. Update date again after 14 days

I'm trying to write some javascript that tracks an event that occurs every 14 days, so I want to display a NextEvent date and a LastEvent date.
Once the current date == NextEvent date, then that date would become the LastEvent date, and the new NextEvent date would become the current date + 14 days.
I've got this so far, but I don't know how I'd go about updating the dates after 14 days has passed. Only really know HTML, but trying to self-learn more. This has stumped me though.
Any help appreciated!
<script>
var last = new Date();
last.setFullYear(2020, 07, 14);
document.write(""+last);
</script>
<script>
var next = last;
next.setDate(next.getDate() + 14);
document.write(""+next);
</script>
I'm not sure I understand your question correctly. You are searching for a way that updates the date after 14 days? You could use the localStorage and save the date.
Now if you load the site, you would load the date from the localStorage and compare it to the current date to check if 14 days has passed. If it has, just overwrite the value in localStorage to update it. Otherwise is there no value, you would just write the value in the localStorage.
Here is a reference, how to use the localStorage: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

how can I disable particular date of input type="date" from JavaScript

I have input type="date" in my html page and I want to disable particular date through JavaScript. How can I do that?
I have tried to disable using getElementById but its disabling complete date input.
You can add a min or max attribute to the input type=date. The date must be in ISO format (yyyy-mm-dd). This is supported in many mobile browsers and current versions of Chrome, although users can manually enter an invalid date without using the datepicker.
<input name="somedate" type="date" min="2017-11-25">
The min and max attributes must be a full date; there's no way to specify "today" or "+0". To do that, you'll need to use JavaScript or a server-side language:
var today = new Date().toISOString().split('T')[0];
document.getElementsByName("somedate")[0].setAttribute('min', today);
What we can’t do yet, however, is eliminate classes of days from our input. We can’t, for example, prevent selection of weekends or disallow Mondays purely through markup. Instead, we’ll need to do a little more work, using the HTML5 validation API, and the native JavaScript Date object.
code that will display an error if the date selected is a Monday.
var date = document.querySelector('[type=date]');
function noMondays(e){
var day = new Date( e.target.value ).getUTCDay();
// Days in JS range from 0-6 where 0 is Sunday and 6 is Saturday
if( day == 1 ){
e.target.setCustomValidity('OH NOES! We hate Mondays! Please pick any day but Monday.');
} else {
e.target.setCustomValidity('');
}
}
date.addEventListener('input',noMondays);
You could set a maximum/minimum on your date attribute like shown over here: https://www.w3schools.com/tags/att_input_min.asp
This however does not let you disable specific dates. If you really want this I would check if the selected date is allowed on posting the form.
You could get the selected date value on a submit like this in JQuery:
$('#submit').on('click', function(){
var date = new Date($('#date-input').val());
day = date.getDate();
month = date.getMonth() + 1;
year = date.getFullYear();
//Check here if date, month and year combination is allowed
});
In this example we have a date element with id 'date-input' and a button with id 'submit'.
Note that you should also check if the date is allowed on the server side.

How to make bootstrap datepicker pick last day of the month instead of first day when minViewMode : 1

I'm using this version of Bootstrap DatePicker: http://eternicode.github.io/bootstrap-datepicker/ (the range type), and i have uploaded my demo on JSFiddle on here: http://jsfiddle.net/qs5co179/6/
The relevant JavaScript:
$('#sandbox-container .input-daterange').datepicker({
format: "dd/mm/yyyy",
minViewMode : 1
});
I have set the parameter minViewMode : 1 so I can view only months on calendar instead of full days, the reason is that I want to strict the user to enter:
1st day of the month in: input name="start"
and strict them too to enter only the last day of the month in: input name="end" (but the default is always 1st day of the month when you click)
For example my data entry that i am looking for like below:
From: 01/07/2015 - To: 30/09/2015.. in this format (dd/mm/yyyy)
Now I can't find any parameter to set the calender to pick the last day of the month instead of always 1st day when you click on the month in "To:" field.
one more thing also that I want to always make "From:" and "To:" having 3months period and no less, I want always to make the range 3 months minimum for the entery.
Thanks a lot in advance...
You could attach an event handler to the changeDate event (doc), and change the date manually (i.e. add a month, substract a day).
For the date handling part, I would
Get the date parts
Increase the month by one, if its December, then change it to January
Create a new Date instance
date = date.setDate(date.getDate() - 1) to get the correct day
The date parts could be exctracted by simple string slicing:
var day = str.slice(0,2);
var month = str.slice(3,5);
var year = str.slice(6,10);

Calculate date from user input

I'm trying to create a sort of Date Calculator widget, where dates can be generated based on user inputs to different fields. Thought being if you didn't know the exact date bbut knew it was so many months/years/days ago, you could generate the date using this widget. In this example, I want to find the date of an event "X" months ago. User inputs number of months ago in field, then a calculation is made to output to the text string saying, the date of the procedure was xx/xx/xxxx.
Here's my fiddle.
html:
Today’s Date:
<label for="monthsago" class="col-sm-2 control-label">How many Months ago?</label>
Date of Procedure was xx/xx/xxxx.
In all the examples I see here or by googling, it seems the dates are being set in the date object like new Date(2000, 0, 1); I want to use the input fields to generate the date objects calculated. I'm very much a novice at javascript so this is throwing me for a loop. Any input/help greatly appreciated.
Why not just subtract the month from a date object
$('#months').on('input', function () {
var date = new Date();
var month = date.getMonth();
date.setMonth(month-this.value);
$('#procedureMonths').text(date.toString());
});
FIDDLE

CalendarExtender saying the wrong date is selected, possibly timezone related

I have a page with a TextBox and a CalendarExtender that is supposed to allow me to detect what date is selected. However, this is reporting the date that isn't selected.
<asp:TextBox ID="tbEffectiveDate" runat="server"
CssClass="input-small"
MaxLength="10"
Text='<%# Bind("NewEffectiveDate", "{0:MM/dd/yyyy}") %>'>
</asp:TextBox>
<ajaxToolkit:CalendarExtender ID="atkEffectiveDate" runat="server"
FirstDayOfWeek="Sunday"
TargetControlID="tbEffectiveDate"
Format="MM/dd/yyyy"
OnClientDateSelectionChanged="CheckForSunday">
</ajaxToolkit:CalendarExtender>
Essentially I'm making sure the user has selected a Sunday, but when I select a day on the calendar, the JavaScript says it is a day before. I'm perplexed.
function CheckForSunday(sender, args) {
var selectedDate = new Date();
selectedDate = sender.get_selectedDate();
// Both of these show the date before the date was selected
alert(sender.get_selectedDate());
if (selectedDate.getDay() != 0) {
// not a Sunday
var sunday = selectedDate;
// calculated the nearest Sunday
sunday.setDate(selectedDate.getDate() - selectedDate.getDay());
sender.set_selectedDate(sunday);
// tell the user that the date wasn't a Sunday
// and that the previous Sunday was selected.
$("#must-be-sunday").modal("show");
}
}
For example, if I select a Sunday, such as May 5th:
Then at the line alert(sender.get_selectedDate());, it displays
This is saying Saturday, May 4th is selected instead of May 5th. Since in my locale, we are -0700 and this is displaying 7 hours before midnight on the 5th, I'm guessing this has something to do with the timezone.
Does anyone know what may be causing this and how to fix it so it doesn't work with the time and only the date selected?
As usual, after writing everything out into a question on here, I've resolved my issue. This was indeed due to timezones, but still is very awkward. If someone has a better solution, I'd love to hear it.
Using getTimezoneOffset() and the solution from How to add 30 minutes to a JavaScript Date object?, I created a calculation to fix this.
var selectedDate = sender.get_selectedDate();
// get the timezone offset in minutes
var timeOffsetMinutes = selectedDate.getTimezoneOffset();
// Convert minutes into milliseconds and create a new date based on the minutes.
var correctedDate = new Date(selectedDate.getTime() + timeOffsetMinutes * 60000);
This corrected my issue and I get the date needed.
You right that the problem due to timezones as CalendarExtender use UTC dates for each day cell value. If you want to check day of week selected you may use Date.getUTCDay() function instead of the Date.getDay() and getUTCDate() instead of getDate() in OnClientDateSelectionChanged handler.

Categories

Resources