PHP: Date range selection automatically - javascript

I have 3 input fields all together.
Contract period: 1 years(for example)
start date : 30 - 1- 2012 (for example)
end date : ????
(Can we get the end date automatically according to the contract period mentioned, which mean if the date after 1 year is 30-1-2013 can we get it automatically in the third field after mentioning the first and second field).

Possible, using onSelect option of jQuery datepicker.
1) get the value of contract year and parse it as integer.
var addYears = parseInt($('#contract').val(), 10);
2) Split the selected date in startDate, as below
var t = date.split('/');
3) Now add the years and parse it as Date object.
var fin = new Date(parseInt(t[2], 10) + addYears, --t[0], t[1]);
Finally,
HTML:
In years only:
<input id="contract" type="text" />
<input id="start" type="text" />
<input id="end" type="text" />
JS:
$('#end').datepicker();
$('#start').datepicker({
onSelect: function (date, args) {
var addYears = parseInt($('#contract').val());
var t = date.split('/');
var fin = new Date(parseInt(t[2], 10) + addYears, --t[0], t[1]);
$('#end').datepicker("setDate", fin);
}
});
JSFiddle

Related

how to get date-picker (only month and year) and display it in mozilla firefox

I want create input fields where user can add month and year. I try with (see below), but Mozilla Firefox doesn't support.
<input type="month" id="start" name="start">
Does anyone know the alternative how can I add month and year for all browsers ?
Either you can try
The first method
// define variables
var nativePicker = document.querySelector('.nativeDatePicker');
var fallbackPicker = document.querySelector('.fallbackDatePicker');
var fallbackLabel = document.querySelector('.fallbackLabel');
var yearSelect = document.querySelector('#year');
var monthSelect = document.querySelector('#month');
// hide fallback initially
fallbackPicker.style.display = 'none';
fallbackLabel.style.display = 'none';
// test whether a new date input falls back to a text input or not
var test = document.createElement('input');
try {
test.type = 'month';
} catch (e) {
console.log(e.description);
}
// if it does, run the code inside the if() {} block
if(test.type === 'text') {
// hide the native picker and show the fallback
nativePicker.style.display = 'none';
fallbackPicker.style.display = 'block';
fallbackLabel.style.display = 'block';
// populate the years dynamically
// (the months are always the same, therefore hardcoded)
populateYears();
}
function populateYears() {
// get the current year as a number
var date = new Date();
var year = date.getFullYear();
// Make this year, and the 100 years before it available in the year <select>
for(var i = 0; i <= 100; i++) {
var option = document.createElement('option');
option.textContent = year-i;
yearSelect.appendChild(option);
}
}
<form>
<div class="nativeDatePicker">
<label for="month-visit">What month would you like to visit us?</label>
<input type="month" id="month-visit" name="month-visit">
<span class="validity"></span>
</div>
<p class="fallbackLabel">What month would you like to visit us?</p>
<div class="fallbackDatePicker">
<div>
<span>
<label for="month">Month:</label>
<select id="month" name="month">
<option selected>January</option>
<option>February</option>
<option>March</option>
<option>April</option>
<option>May</option>
<option>June</option>
<option>July</option>
<option>August</option>
<option>September</option>
<option>October</option>
<option>November</option>
<option>December</option>
</select>
</span>
<span>
<label for="year">Year:</label>
<select id="year" name="year">
</select>
</span>
</div>
</div>
</form>
Or using an JS library
http://jsfiddle.net/yLjDH/
I have solved it similar like rgedit.
I have two arrays, one with months and second is with years (i only used this and next two years, like below).
[new Date().getFullYear(), new Date().getFullYear() + 1, new Date().getFullYear() + 2,]
then i have two select tags where i used forEach for months and years and after that I made the date I needed.
let date = myMonth + '-' + myYear
let newDate = new Date(date)
After i have month and year I can find first and last day in month, what i needed.
It's not pretty, but it works :D Thank you guys.
ANSWER
— setDate() sets the day of the month of a date.
const d = new Date();
d.setDate(0);
— Set the day of the month in a specified date:
const d = new Date("July 21, 1983 01:15:00");
d.setDate(15);
— The setMonth() method sets the month of a date object. Note: January is 0, February is 1, and so on.
Set the month to 4 (May):
const d = new Date();
d.setMonth(4);
— Set the month to 4 (May) and the day to 20:
const d = new Date();
d.setMonth(4, 20);
— setFullYear() sets the year of a date. setFullYear() can also set month and day.
const d = new Date();
d.setFullYear(2020);
const d = new Date();
d.setFullYear(2020, 10, 3);
ANSWER
To set and get the input type date in dd-mm-yyyy format we will use type attribute. The type attribute is used to define a date picker or control field. In this attribute, you can set the range from which day-month-year to which day-month-year date can be selected from. If min and max values are not set then default min value is set to “01-01-1920” and default max value is set to “01-01-2120”.
body {
text-align: center;
}
h1 {
color: green;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h3>Get input date in dd-mm-yyyy format</h3>
<label for="start"> Enter the Date: </label>
<input type="date" name="begin"
placeholder="dd-mm-yyyy" value=""
min="1997-01-01" max="2030-12-31">
</body>
</html>

Add one day to date string in javascript

I am setting the min of checkOut as the value of checkIn. My problem comes that i need to add one day to firstdate. (Should not be able to check out on or before the check in day.)
<script>
function updatedate() {
var firstdate = document.getElementById("checkIn").value;
document.getElementById("checkOut").value = "";
document.getElementById("checkOut").setAttribute("min",firstdate);
}
</script>
Check In
<input type="date" id="checkIn" onchange="updatedate();" name="checkin">
Check out
<input type="date" id="checkOut" min="" name="checkout">
It's sort of do-able but it only works in Chrome since that's the only browser that supports a date input at the moment. Oh, and this solution uses momentjs because parsing a date and correctly adding 1 day to it is way harder that it sounds.
function updatedate() {
var checkin = document.getElementById("checkIn").value;
checkin = moment(checkin);
var checkout = checkin.add(1, 'd');
document.getElementById("checkOut").setAttribute("min", checkout.format('YYYY-MM-DD'));
}
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet"/>
<div class="container">
Check In
<input type="date" id="checkIn" onchange="updatedate();" name="checkin">Check out
<input type="date" id="checkOut" min="" name="checkout">
</div>
A momentless solution is to parse the checkinDate into a JS date and and then create a new date whilst adding one day to the checkinDate. Though yeah, momentJS is the goto library when dealing with dates.
JSfiddle here:
https://jsfiddle.net/xugajae5/
There was a bit of a hack in getting the min format that the input expected:
var checkoutDateFormat = checkoutDate.toISOString().split('T')[0];
Not all browsers in use support input type date, so you'll need to deal with that to start with.
Then, you can convert the value of firstdate to a Date object, add a day, then get back a date in the required format. Your issue however is that the value of the date input (which is an ISO 8601 format date string) is treated as local, but the Date constructor will treat it as UTC.
So you need to parse the string as a local date, then add the day, then get back a string in the right format. The code below is just an example, you may wish to use a library for the date manipulation. Just remember not to parse the date string with the Date constructor.
function getTomorrow(el) {
var form = el.form;
var start = parseISOAsLocal(form.start.value);
// Check if input date was valid
if (!start.getTime()) {
form.tomorrow.value = '';
form.start.value = 'Invalid date';
return;
}
start.setDate(start.getDate() + 1);
form.tomorrow.value = formatISODate(start);
}
function parseISOAsLocal(s) {
var b = s.split(/\D/);
var d = new Date(b[0], --b[1], b[2]);
return d && d.getMonth() == b[1]? d : new Date(NaN);
}
function formatISODate(date) {
return ('000' + date.getFullYear()).slice(-4) + '-' +
('0' + (date.getMonth() + 1)).slice(-2) + '-' +
('0' + date.getDate()).slice(-2);
}
<form>
Start (yyyy-mm-dd):
<input type="date" name="start" value="2016-08-31"><br>
Tomorrow: <input type="date" name="tomorrow" readonly><br>
<input type="button" onclick="getTomorrow(this)"
value="Show tomorrow">
</form>
<script>
function updatedate(){
var checkInValue = document.getElementById("checkIn").value;
var checkInDate = Date.parse(checkInValue);
var minDate = new Date(checkInDate + 24 * 3600 * 1000);
document.getElementById("checkOut").setAttribute("min", minDate.toDateString());
}
</script>

Firefox date format

I have created a webpage which calculates the weeks and days between two dates.
In chrome this page works and gives me the output of 4 weeks and two days for the dates 01/01/2016 and 01/31/2016 but firefox gives me the output of 130 weeks and two days.
How would I got about changing this to get the output of chrome.
Many thanks
<html>
<head>
<title>Time Between Dates Calculator</title>
<script src="dateCalc.js"></script>
</head>
<body>
<h1>Calculate the Amount of Time Between Dates:</h1>
<form>
Enter Date 1 (mm/dd/yyyy): <input type="date" id="date1" name="date1" required> <br />
Enter Date 2 (mm/dd/yyyy): <input type="date" id="date2" name="date2" required> <br />
<input type="submit" onclick="datecalc()" Value="Get Weeks and days">
</form>
</body>
</html>
***********************************************************************
function datecalc()
{
firstDate = document.getElementById("date1").value;
secondDate = document.getElementById("date2").value;
/*window.alert(firstDate);
window.alert(secondDate);*/
firstDateMs = new Date(firstDate).getTime();
secondDateMs = new Date(secondDate).getTime();
msPerDay = 24 * 60 * 60 * 1000;
msLeft = (secondDateMs - firstDateMs);
daysLeft = Math.round(msLeft/msPerDay);
weeksLeft = Math.round(daysLeft/7);
total = (daysLeft-(weeksLeft*7))
window.alert("The difference between these days is: " + weeksLeft + " weeks and " + total + " days.");
}
one solution is to use .split("/") on your input strings, then use the
new Date(year, month, day); constructor.
Also January is 0 and December is 11 in Javascript date
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date
this will remove any ambiguity from possible string interpretation of the date.
firstDate = document.getElementById("date1").value;
secondDate = document.getElementById("date2").value;
/*window.alert(firstDate);
window.alert(secondDate);*/
firstDate.split("/");
secondDate.split("/");
firstDateMs = new Date(parseInt(firstDate[2]), parseInt(firstDate[0]) - 1, parseInt(firstDate[1])).getTime();
secondDateMs = new Date(parseInt(secondDate[2]), parseInt(secondDate[0]) - 1, parseInt(secondDate[1])).getTime();
The submit listener should be on the form, not the submit button, since the form can be submitted without clicking the button. Also, the date strings should be manually parsed to dates and since they depend on user input, the values validated. It can also make life easier if a reference to the form is passed by the handler so controls are accessed by name rather than getElementById.
Input type date is not well supported and creates more issues than it solves for now, so better to use type text (or use your own date picker). The following uses input type text and manually parses and validates the string in m/d/y format.
For a real form, it would be better to validate each date separately and put an error message for the one(s) that are invalid, also to echo the parsed date to the screen so the user can see that the code is using the date as they expect (e.g. 1/2/2016 comes out as 2 January not 1 February).
Some code…
function datecalc(form) {
var d1 = parseMDY(form.date1.value);
var d2 = parseMDY(form.date2.value);
var msDay = 8.64e7;
var msWeek = msDay * 7;
var result;
// Deal with in valid input
if (isNaN(+d1) || isNaN(+d2)) {
result = 'Invalid date';
} else {
// Get weeks and days
var diff = d2 - d1;
result = (diff/msWeek | 0) + ' weeks ' +
Math.round((diff % msWeek)/msDay | 0) + ' days';
}
// Should return an array of say [weeks, days] and leave formatting
// to some other function.
form.result.value = result;
}
function parseMDY(s) {
var b = s.split(/\D/);
var d = new Date(b[2], --b[0], b[1]);
return d && d.getMonth() == b[0]? d : new Date(NaN);
}
<form onsubmit="datecalc(this); return false;">
Enter Date 1 (mm/dd/yyyy): <input type="text" name="date1" value="3/1/2016"><br>
Enter Date 2 (mm/dd/yyyy): <input type="text" name="date2" value="3/23/2016"><br>
<input type="reset"> <input type="submit" Value="Get Weeks and days"><br>
<input type="text" name="result" readonly>
</form>
I guess you're rounding the days to remove daylight saving errors, be careful with that. An alternative is to get the difference in days from the date values and not create date objects at all. That removes any issues with DST (but validating the dates takes about 3 lines more code).

how to add days / weeks from separate field in start date to get end date in datepicker?

In my form , I have 3 fields.
<input name="course_duration" id="course_duration" type="text"> (A numeric value which denotes 'Weeks'
<input name="course_start" id="course_start" type="text">
<input name="course_end" id="course_end" type="text">
I am using datepicker jquery and I want to fillup course_end date automatically by adding number of weeks from value inserted in course_duration field + course_start date
currently I am using following javascript code to popup calendar and selecting dates for course_start and course_end manually.
<script type="text/javascript">
$(document).ready(function() {
$('#course_start').datepicker({dateFormat: 'yy-mm-dd'});
$('#course_end').datepicker({dateFormat: 'yy-mm-dd'});
});
</script>
JSFIDDLE
// Get the week from course_duration
var weeks = $('#course_duration').val();
// Get the selected date from startDate
var startDate = $('#course_start').datepicker('getDate');
var d = new Date(startDate);
// Add weeks to the selected date, multiply with 7 to get days
var newDate = new Date(d.getFullYear(), d.getMonth(), d.getDate() + weeks * 7);
// Set the new date to the course endDate
$('#course_end').datepicker('setDate', newDate);
Demo

How to auto format textbox inputs

<tr>
<td><label>Birthdate</label>
<input type="text" placeholder="mm/dd/yyyy" name="birthdate" maxlength="10"/>
</td>
</tr>
Well, my code is working but I want my "input type text" to auto format like a date (html 5 input type=date) because in my Servlet I convert it to Age.
The problem is that, if I use the "input type=date" the conversion is error so I decided to use "input type=text" and it's working. So is it possible to auto put "/" in this format "mm/dd/yyyy"? For example, if the user input 2 character an "/" will auto input etc.
Servlet for birthdate to Age
String birthdate = request.getParameter("birthdate");
int monthDOB = Integer.parseInt(birthdate.substring(0, 2));
int dayDOB = Integer.parseInt(birthdate.substring(3, 5));
int yearDOB = Integer.parseInt(birthdate.substring(6, 10));
DateFormat dateFormat = new SimpleDateFormat("MM");
java.util.Date date = new java.util.Date();
int thisMonth = Integer.parseInt(dateFormat.format(date));
dateFormat = new SimpleDateFormat("dd");
date = new java.util.Date();
int thisDay = Integer.parseInt(dateFormat.format(date));
dateFormat = new SimpleDateFormat("YYYY");
date = new java.util.Date();
int thisYear = Integer.parseInt(dateFormat.format(date));
int calAge = thisYear - yearDOB;
if (thisMonth < monthDOB) {
calAge = calAge - 1;
}
if (thisMonth == monthDOB && thisDay < dayDOB) {
calAge = calAge - 1;
}
String age = Integer.toString(calAge);
Update in the form
<tr>
<td><label for="inputName">Birthdate</label>
<input type="text" placeholder="mm/dd/yyyy" id="input_date" name="birthdate" maxlength="10" />
</td>
</tr>
Update in the source
<script src="../scripts/formatter.js"></script>
<script src="../scripts/formatter.min.js"></script>
<script src="../scripts/jquery.formatter.js"></script>
<script src="../scripts/jquery.formatter.min.js"></script>
Added Script
<script>
$('#input_date').formatter({
'pattern': '{{99}}/{{99}}/{{9999}}',
'persistent': true
});
</script>
I also tried the javascript but it's not working...
I've been watching a project on GitHub (and providing feedback to improve it) for just such kind of formatting called formatter.js http://firstopinion.github.io/formatter.js/demos.html This might be just the thing you're looking for.
This wouldn't stop you from typing in dates like the 53rd of May... but it will help you format.
new Formatter(document.getElementById('date-input'), {
'pattern': '{{99}}/{{99}}/{{9999}}',
'persistent': true
});
or
$('#date-input').formatter({
'pattern': '{{99}}/{{99}}/{{9999}}',
'persistent': true
});
I have an alternative that works with a jquery-ui datepicker, without formatter.js. It is intended to be called from the keyup and change events. It adds zero padding. It works with various supported date formats by constructing expressions from the dateFormat string. I can't think of a way to do it with fewer than three replaces.
// Example: mm/dd/yy or yy-mm-dd
var format = $(".ui-datepicker").datepicker("option", "dateFormat");
var match = new RegExp(format
.replace(/(\w+)\W(\w+)\W(\w+)/, "^\\s*($1)\\W*($2)?\\W*($3)?([0-9]*).*")
.replace(/mm|dd/g, "\\d{2}")
.replace(/yy/g, "\\d{4}"));
var replace = "$1/$2/$3$4"
.replace(/\//g, format.match(/\W/));
function doFormat(target)
{
target.value = target.value
.replace(/(^|\W)(?=\d\W)/g, "$10") // padding
.replace(match, replace) // fields
.replace(/(\W)+/g, "$1"); // remove repeats
}
https://jsfiddle.net/4msunL6k/
use datepicker api from jquery
here is the link Datepicker
and here is the working code
<tr>
<td><label>Birthdate</label>
<input type="text" placeholder="mm/dd/yyyy" name="birthdate" id="birthdate" maxlength="10"/>
</td>
</tr>
<script>
$(function() {
$( "#birthdate" ).datepicker();
});
</script>
EDIT
$("input[name='birthdate']:first").keyup(function(e){
var key=String.fromCharCode(e.keyCode);
if(!(key>=0&&key<=9))$(this).val($(this).val().substr(0,$(this).val().length-1));
var value=$(this).val();
if(value.length==2||value.length==5)$(this).val($(this).val()+'/');
});
this is the code that you may need
here is the fiddled code
user2897690 had the right idea but it didn't accept Numpad numbers. So took their javascript and modified it to work.
Here is my interpretation of their code with the added feature.
$("input[name='birthdate']:first").keyup(function(e){
var chars = [48,49,50,51,52,53,54,55,56,57,96,97,98,99,100,101,102,103,104,105];
var key=chars.indexOf(e.keyCode);
console.log(key);
if(key==-1)$(this).val($(this).val().substr(0,$(this).val().length-1));
var value=$(this).val();
if(value.length==2||value.length==5)$(this).val($(this).val()+'/');
});

Categories

Resources