Javascript add year to date and put in html input - javascript

In a view, I have a date that the user must enter.
What I want is that the other dates are automatically filled in with +2 years for one and +5 years for another.
Thank you for your help.
html
<input type="date" th:field="*{date_fabrication}" class="form-control
col-xs-3 col" id="fabId"
th:onblur="majdates()"
th:errorclass="invalid"
th:placeholder="#{fabricationEquipment}"
style="width: 200px;font-size:12px;"
required>
function
<script>
function majdates() {
var recupDate = document.getElementById("fabId").value;
var plusTwoYears = recupDate.setFullYear(date.getFullYear() + 2);
document.getElementById("commissioningId").value = plusTwoYears;
}
</script>
edit : the target date :
<input type="date" th:field="*{date_mise_en_service}" class="form-control col"
id="commissioningId"
th:errorclass="invalid"
th:placeholder="#{commissioningEquipment}"
style="width: 200px;font-size:12px;">
thanks to Rory, the solution below
<script>
document.querySelector('#fabId').addEventListener('blur', e => {
var recupDate = new Date(e.target.value);
var plusTwoYears = new
Date(recupDate.setFullYear(recupDate.getFullYear() + 2));
var formatedPlusTowYears =plusTwoYears.toISOString().slice(0,10);
document.querySelector("#commissioningId").value = formatedPlusTowYears;
document.querySelector("#volumeId").value = formatedPlusTowYears;
});
</script>

Your code is almost there. The main issue is that recupDate will be a string. You need to parse it to a Date object in order to call setFullYear on it.
Also note that the result of setFullYear() will be an epoch timestamp, not a date, so you'll again need to parse the response of that to a Date object - and possibly format it manually depending on the output required.
document.querySelector('#fabId').addEventListener('blur', e => {
var recupDate = new Date(e.target.value);
var plusTwoYears = new Date(recupDate.setFullYear(recupDate.getFullYear() + 2));
document.querySelector("#commissioningId").value = plusTwoYears;
});
input {
width: 200px;
font-size: 12px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="date" class="form-control col-xs-3 col" id="fabId" required />
<input type="text" readonly id="commissioningId" />
Finally, I also changed the logic to use an unobtrusive event handler instead of the onblur attribute, as the latter are no longer good practice.

Related

How to add a certain amount of minutes in a DateTime Input in Javascript

I have two Input Fields like these,
<div class="form-group mb-3">
<label for="">Challenge Start Date and Time</label>
<input type="datetime-local" class="form-control form-control-sm" name="date" id = "date" value=""/>
</div>
<div class="form-group mb-3">
<label for="">Challenge End Date and Time</label>
<input type="datetime-local" class="form-control form-control-sm" name="end_date" id = "end_date" value=""/>
</div>
What I want to do actually is whatever time the user sets in the "Start" Input, that time + 45 minutes should be set to the 2nd Input Field.
So, I tried the following, but unfortunately, due to the conversion of the Input Time into the String, I am unable to call getMinutes() + 45
var now = new Date();
now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
document.getElementById('date').value = now.toISOString().slice(0,16);
now.setMinutes(now.getMinutes() + 45);
document.getElementById('end_date').value = now.toISOString().slice(0,16);
document.getElementById('date').addEventListener('change', (e) => {
const value = e.target.value;
value.setMinutes(value.getMinutes() + 45);
document.getElementById('end_date').value = now.toISOString().slice(0,16);
});
I get this error whenever I change the value of the First Input Field,
Uncaught TypeError: value.getMinutes is not a function
Can anyone please provide an solution to this problem?
Try this
this will change get the input from field1 to field2
const value = new Date(e.target.value);
value.setMinutes(value.getMinutes() + 45);
value.setMinutes(value.getMinutes() - value.getTimezoneOffset());
document.getElementById('end_date').value = value.toISOString().slice(0,16);
You Missed the timezoneminutes minus from the calculated value
Write your onchange function like this:
document.getElementById('date').addEventListener('change', (e) => {
var date = new Date(document.getElementById('date').value);
date.setMinutes(date.getMinutes() - date.getTimezoneOffset());
date.setMinutes(date.getMinutes() + 45);
document.getElementById('end_date').value=date.toISOString().substring(0, 16);
})
The value of a datetime-local field does not return a Date object. It returns a string representation of the date (ISO-8601).
Here you can find more information about the value property of an <input type="datetime-local">
To convert this to a Date object you can just pass the value to the constructor like this:
var myDate = new Date(e.target.value);

How to add minutes to an hour in a datetime-local input?

I am copying the value of an input of type datetime-local (date_start) to another once the user writes in the first one (date_end). However I would like to be able to add 20 minutes more to the result in the second input (date_end) How could I do it?The format is example 10/20/2017 15:00
$("#date_start").keyup(function(){
var value = $(this).val();
$("#date_end").val(value);
});
The normal JQuery selector does not seem to work with this element, so I have used document.querySelector() instead of $(), So please find below my solution, this implements the stepUp() method of the DatetimeLocal object which will increment the value by minutes. Also please note I am adding the click event also in addition to keyup, since it seems necessary for this input element.
var start=document.querySelector('input[type="datetime-local"]#date_start'), end = document.querySelector('input[type="datetime-local"]#date_end')
start.value = start.value;
end.stepUp(20);
$("#date_start").on("click keyup", function(){
end.value = start.value;
end.stepUp(20);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="datetime-local" class="form-control" id="date_start" name="date_start" value="2017-06-01T08:30">
<input type="datetime-local" class="form-control" id="date_end" name="date_end" >
The Javascript equivalent for this will be.
var end = document.querySelector('input[type="datetime-local"]#date_end'), start = document.querySelector('input[type="datetime-local"]#date_start');
end.value = start.value;
end.stepUp(20);
start.addEventListener("click", addMinutes);
start.addEventListener("keyup", addMinutes);
var addMinutes = function(){
end.value = start.value;
end.stepUp(20);
};
<input type="datetime-local" class="form-control" id="date_start" name="date_start" value="2017-06-01T08:30">
<input type="datetime-local" class="form-control" id="date_end" name="date_end" >
try this
$( document ).ready(function() {
DateObj = Date.parse("10/20/2017 16:00");
// vale you get $("#date_end").val(value);
var date = new Date(DateObj+1200000);
console.log(date.toLocaleString('en-US',{ hour12: false }));
});
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>

Display date as dd-mm-yyyy format for input type=date

I have my code :
<input type="date" class="form-control" id="training_date"
name="training_date" placeholder=" select" value=""
onfocus="(this.type='date')"
onfocusout="(this.type='date')" max=<?php echo date('Y-m-d'); ?>>
I need to display my date in following date-format dd-mm-yyyy format in the textbox.
What I would recommend is to make a array with the 12 months of the year (because the will never change)
_currentDate() {
var date = new Date();
for (var i = 0; this.months.length > i; i++) {
if (date.getMonth() === i) {
var displayMonth = this.months[i].month;
}
}
var displayDate = date.getDate() + ' ' + displayMonth + ' ' + date.getFullYear();
return displayDate;
}
Use the value that you return in your function you just need to insert where you want to display it so in your case your input
Hope this helps :)
Please note: <input type="date"> is not supported in IE and Firefox. Hence, it's not good idea to implement it in as it's against robust UI/UX design, and might invite later bugs.
You should use jquery's datepicker, moment.js or combination of both to achieve your requirement.
To close the question and provide what can be done and tested. Here is implementation.
In this example:
I am assigning today's date to <input type="date"> by forming a date string in yyyy-mm-dd format and setting attribute value
whenever I am changing the the date in #datepicker, I am forming a date string in dd-mm-yyyy format and providing it as value to #textbox
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var d = new Date();
function twoDigitDate(d){
return ((d.getDate()).toString().length == 1) ? "0"+(d.getDate()).toString() : (d.getDate()).toString();
};
function twoDigitMonth(d){
return ((d.getMonth()+1).toString().length == 1) ? "0"+(d.getMonth()+1).toString() : (d.getMonth()+1).toString();
};
var today_ISO_date = d.getFullYear()+"-"+twoDigitMonth(d)+"-"+twoDigitDate(d); // in yyyy-mm-dd format
document.getElementById('datepicker').setAttribute("value", today_ISO_date);
var dd_mm_yyyy;
$("#datepicker").change( function(){
changedDate = $(this).val(); //in yyyy-mm-dd format obtained from datepicker
var date = new Date(changedDate);
dd_mm_yyyy = twoDigitDate(date)+"-"+twoDigitMonth(date)+"-"+date.getFullYear(); // in dd-mm-yyyy format
$('#textbox').val(dd_mm_yyyy);
//console.log($(this).val());
//console.log("Date picker clicked");
});
});
</script>
</head>
<body>
<div style="width: 50%;height:50px; float:left;">
Enter your Birthday!!:<br>
<input id="datepicker" type="date" name="bday" style="margin-bottom: 200px;"></br><br>
</div>
<div style="width: 50%;height:50px; float:right;">
Date chosen(dd-mm-yyyy):<br>
<input id="textbox" type="text" value="dd-mm-yyyy"></input>
</div>
</br></br></br></br></br></br>
<p><strong>Note:</strong> type="date" is not supported in Firefox, or Internet Explorer 11 and earlier versions.</p>
</body>
</html>
You can use the below code to achieve this.
<input type="date" class="form-control" id="training_date" name="training_date" placeholder=" select" value="" onfocus="(this.type='date')" onfocusout="(this.type='date')" pattern="\d{1,2}/\d{1,2}/\d{4}" >

Combining Date and Time input strings as a Date object

I have two input tags for picking date and time from user.
<p>Start Date</p><p> <input ng-model="sdate" type="date" ></p>
<p>Start Time</p><p> <input ng-model="stime" type="time" ></p>
These two values are passed to a function where I want to combine these two input values as a Date object:
new Date(y, m, d, hh, mm, a)
Which I can then use to plot an event's details in a Calendar. How can I combine these two values? I have tried:
start:new Date(sdate + stime)
start:new Date(sdate , stime)
start: new Date(sdate.getFullYear() + sdate.getMonth() + sdate.getDate() + stime.getHours + stime.getMinutes())
But none of what I have tried is working.
How do I achieve this when using AngularJS?
In angular it would go something like this:
Controller:
function exampleController($scope) {
$scope.title = "$Watch sample";
$scope.$watch('sdate', function() {
tryCombineDateTime();
});
$scope.$watch('stime', function() {
tryCombineDateTime();
});
function tryCombineDateTime() {
if($scope.sdate && $scope.stime) {
var dateParts = $scope.sdate.split('-');
var timeParts = $scope.stime.split(':');
if(dateParts && timeParts) {
dateParts[1] -= 1;
$scope.fullDate = new Date(Date.UTC.apply(undefined,dateParts.concat(timeParts))).toISOString();
}
}
}
}
HTML
<div ng-app ng-controller="exampleController">
<h2>{{title}}</h2>
<p>Start Date</p><p> <input ng-model="sdate" type="date" ></p>
<p>Start Time</p><p> <input ng-model="stime" type="time" ></p>
{{fullDate}}
</div>
You need to make use of the $watch listener on a variable when it changes, then call your function.
Note: it would be even better if you make a directive for this.
Fidle
A very naive approach to combine these two is to split date-components and time-components and make a string. Then make a new Date object using this string.
Input is taken from here:
<p>Start Date</p><p> <input ng-model="sdate" type="date" ></p>
<p>Start Time</p><p> <input ng-model="stime" type="time" ></p>
Then in script part, split date and time components as follows:
var dd = new Date(sdate).getDate();
var mm = new Date(sdate).getMonth()+1;
var yy = new Date(sdate).getFullYear();
var hh = new Date(stime).getHours();
var ms = new Date(stime).getMinutes();
Then Combine these components to form a string as required(in Calendar):
var x = yy + ',' + mm + ',' + dd + ' ' + hh + ':' + ms;
Now create a new Date object:
var finaldate = new Date(x);
You could do something like this, though this doesn't have anything to do with AngularJS and I can't test on older browsers. I am assuming that you are entering date/time as UTC and I am using Date to create an ISO8601 timestamp as an output. Also assumes that you are using a modern browser that supports HTML5 and ECMA5, otherwise you will need to modify the code.
HTML
<p>Start Date</p><p> <input id="myDate" ng-model="sdate" type="date" ></p>
<p>Start Time</p><p> <input id="myTime" ng-model="stime" type="time" ></p>
<div id="myIso"></div>
Javasceipt
var myIso = document.getElementById('myIso'),
dateParts,
timeParts;
function joinPartsAsDate() {
if (dateParts && dateParts.length === 3 && timeParts && timeParts.length === 2) {
// dateParts[1] -= 1; could be done here
myIso.textContent = new Date(Date.UTC.apply(undefined, dateParts.concat(timeParts))).toISOString();
} else {
myIso.textContent = '';
}
}
document.getElementById('myDate').addEventListener('change', function (e) {
dateParts = e.target.value.split('-');
if (dateParts[1]) { // this could be done in joinPartsAsDate, here for clarity
dateParts[1] -= 1;
}
joinPartsAsDate();
}, false);
document.getElementById('myTime').addEventListener('change', function (e) {
timeParts = e.target.value.split(':');
joinPartsAsDate();
}, false);
On jsFiddle
After testing all stuff described here, i found a very simple solution.
In my view i have
<input type="date" ng-model="tsc.untilDate">
<input type="time" ng-model="tsc.untilTime">
In my Angular Controller both model elements are objects from type Date by default.
With input type="date" the time of this Date object is always 00:00.
With input type="time" the date part of the Date object ist allways set to today.
So i just read the daytime (if it is set) of the TimeDate Object and set it on the DateObject.
if(tsc.untilTime)
{
tsc.untilDate.setHours(tsc.untilTime.getHours());
tsc.untilDate.setMinutes(tsc.untilTime.getMinutes());
}
For those looking for a compact version install the momentjs library.
npm install moment --save
Add it to your file header.
import * as moment from 'moment';
Then just compose the dateTime object with the fluent interface.
let dateTime = moment(this.sdate)
.startOf('day')
.set('hour', this.sTime.getHours())
.set('minute', this.sTime.getMinutes() )
.toDate();
Try this
const timeAndDate = moment(this.sdate + ' ' + this.sTime.getHours() + ' ' + this.sTime.getMinutes());
console.log(timeAndDate.toDate());

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