I have two input fields with date1 and date2.Below this two fields i need a button that when i press it, will create a number of input fields equal to the number of months between the 2 date fields.
For example i have date1=2012-03-21 and dat2=2012-06-21. It should generate 3 input fields
Can you help me with this one?
Let's assume the HTML looks something like this:
<div id="dateRange">
<input type="text" id="startDate">
<input type="text" id="endDate">
</div>
<div id="monthlyEntries"/>
Now, a month is not a uniform number of days ("30 days has September, April, June,and November..."), so I'm guessing the day portion of the dates don't matter.
Then, the javascript to call on change (or clicking a button, or whatever), would look something like this:
function buildMonthlyEntries() {
var startDate = new Date(document.getElementById('startDate').value);
var endDate = new Date(document.getElementById('endDate').value);
if(startDate == "Invalid Date" || endDate == "Invalid Date") { return null; }
var entryCount = (endDate.getMonth() + endDate.getFullYear()*12) - (startDate.getMonth() + startDate.getFullYear()*12);
var monthlyEntries = document.getElementById('monthlyEntries');
monthlyEntries.innerHTML = "";
for(var i = 0; i < entryCount; i++) {
var textElement = document.createElement('input');
textElement.setAttribute('type', 'text');
textElement.setAttribute('id', 'entry' + i);
monthlyEntries.appendChild(textElement);
}
return null;
}
You can run a loop based upon the difference in the dates. In pseudo code it would be something like
var difference = month2 - month1;
for(x=0;x<difference,x++){
add inputfield;
}
Related
I want to subtract a user input years from another input years, but so far I had no luck.
I'll create a snippet where you can play.
What I'm trying to do is to make an input field (A) to enter years only. Then after that select any date and subtract it from the input year (A) (date and month are fixed like 31.03.input_year)...
$(document).on('change', '#year_select', function() {
calculate();
});
$(document).on('change', '#new_date', function() {
calculate();
});
function calculate() {
var year_enter = $('#year_select').val();
var current_year = year_enter+'-03-31';
var new_date = $('#new_date').val();
if(year_enter != '') {
//alert(current_year);
}
if(new_date != '') {
//alert(new_date);
var total = new_date - current_year;
$('#answer').val(total);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Enter years (A)</p>
<input type="number" id="year_select" min="0" placeholder="Eg: 2018, 2001">
<br>
<p>Select Date (B)</p>
<input type="date" id="new_date">
<p>(A - B)</p>
<input type="text" readonly id="answer">
I always get NaN value, my subtract method is incorrect I guess. I tried using setDate(), getDate() etc, but I don't understand the logic.
Thanks in advance...
You can use new Date() to type cast them into date in order to do arithmetic
$(document).on('change', '#year_select', function() {
calculate();
});
$(document).on('change', '#new_date', function() {
calculate();
});
function calculate() {
var year_enter = $('#year_select').val();
var current_year = new Date(year_enter + '-03-31');
var new_date = new Date($('#new_date').val());
if (year_enter != '') {
}
if (new_date != '' && year_enter != '') {
if (current_year < new_date) {
$('#answer').val('A must be greater than B');
return;
}
var total = Math.round(Math.abs((current_year.getTime() - new_date.getTime()) / (24*60*60*1000)));
$('#answer').val(total);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Enter years (A)</p>
<input type="number" id="year_select" min="0" placeholder="Eg: 2018, 2001"><span style="opacity: 0.5;"> this currently has fixed -month-day(-03-31) </span>
<br>
<p>Select Date (B)</p>
<input type="date" id="new_date">
<p>(A - B)</p>
<input type="text" readonly id="answer">
Dates can be tricky to handle, but the moment library makes it a lot easier. In my example I take the input of the two fields, parse them into a moment object and calculate their difference in a duration. You can read more on duration in the Moment.js docs.
The code snippet difference is expressed in days. In case you want to change it to months, or years, update the below line.
log(Math.round(duration.as('days')) + 'days');
You can also include several if statements, to check if the difference is a year, display the result in years. If not, and there's a full month, express the result in months and so on.
Here's a working example in days.
$(document).on('change', '#year_select', function() {
calculate();
});
$(document).on('change', '#new_date', function() {
calculate();
});
function calculate() {
var yearSelect = document.querySelector('#year_select').value;
var newDate = document.querySelector('#new_date').value;
var first_date = new window.moment('31-03-' + yearSelect, 'DD-MM-YYYY');
var second_date = new window.moment(newDate, 'YYYY-MM-DD');
if(yearSelect.length !== 4 || newDate === '') {
log('');
return;
}
var duration = window.moment.duration(first_date.diff(second_date));
log(Math.round(duration.as('days')) + 'days');
}
function log(value) {
var answer = document.querySelector('#answer');
answer.value = value;
}
<script src="https://cdn.jsdelivr.net/momentjs/2.10.6/moment-with-locales.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Enter years (A)</p>
<input type="number" id="year_select" min="0" placeholder="Eg: 2018, 2001">
<br>
<p>Select Date (B)</p>
<input type="date" id="new_date">
<p>(A - B)</p>
<input type="text" readonly id="answer">
NOTE: There are a few discussions out there on how to format a date/duration, e.g. 1 year, 2 months, 5 days. Have a look at a possible solution at these discussions if you want something like this.
How can I format time durations exactly using Moment.js?
How do I use format() on a moment.js duration?
I need to convert an <input type="date"> value in a timestamp. This is my HTML code:
<input type="date" name="date_end" id="date_end">
This field has a value that I have put like 25/10/2017
My jQuery code is:
var dataEnd = $('[name="date_end"]').val();
if (!dataEnd) {
return false;
} else {
var timestamp_end=$('[name="date_start"]').val().getTime();
console.log("TIMESTAMP END "+timestamp_end);
.....
}
But this is not working... why not?
make a new Date() passing the value of your input as parameter, then call getTime(). here an example:
$('[name="date_end"]').on('change',function() {
var dataEnd = $(this).val();
console.log((new Date(dataEnd)).getTime());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="date" name="date_end" id="date_end">
do this
var dateEnd = $('#date_end').val()
var var timestamp_end = Date.parse(date_end)
or
in a single line
var timestamp_end = Date.parse($('#date_end').val())
it works and it's clean
Here is a Solution ( Using pure js ) , I used the unary plus operator operator after converting the value into javascript date object.
function checkDateValue(){
var dateConvertedToTimestamp = (+new Date(document.getElementById('date_value').value));
document.getElementById('date_value_timestamp').innerHTML = dateConvertedToTimestamp ;
}
<input type='date' id='date_value'>
<button onClick='checkDateValue()'> Submit </button>
<div>Timestamp:- <span id='date_value_timestamp'></span></div>
I needed an UNIX timestamp and updated Partha Roy's anwser for my needs.
Javascript :
document.getElementById('dateInput').addEventListener('change', function (){
let inputDate = document.getElementById('dateInput').value ;
let dateConvertedToTimestamp = new Date(inputDate).getTime() ;
console.log(dateConvertedToTimestamp) ;
document.getElementById('resultTime').value = dateConvertedToTimestamp / 1000 ;
}) ;
The /1000 division convert to UNIX timestamp + I track all input change and not only when the form is submited.
HTML :
<input type='date' id='dateInput'>
<input type='hidden' id='resultTime' name='dateTimestamp'>
Don't forget date input are still not well supported, so we can easily adapt this code with classic numbers input.
You can use following code
<script type="text/javascript">
var d = new Date(parseInt($('[name="date_start"]').val()));
var n = d.getTime();
console.log(n);
</script>
I'm checking a date entered with a datepicker control in jquery from an Html.TextBoxFor helper:
<%=Html.TextBoxFor(c => Model.mydate, new { #class = "datepicker", maxlength = 10, #onBlur = "chkDate"})%>
The datepicker mask for the textbox appears to be MM/DD/YYYY . So, my script checks for an underscore and displays an error. This works if the user igonores the datepicker and tries to enter a date freehand but not if the datepicker is used. When a date is chosen, the value passed to my script is still underscores and no value. Here's my script:
<script type="text/javascript">
$(document).on("blur", "input[name=mydate]",
function chkDate() {
var len = $("input[name=mydate]").val().length;
var date = $("input[name=mydate]").val();
var month = date.slice(0, 2);
var day = date.slice(3, 5);
var year = date.slice(6, 10);
alert("chkBirthday " + month);
if (month == '__') {
document.getElementById("MainContent_ErrorMessage").visibility = 'visible';
document.getElementById("MainContent_ErrorMessage").innerHTML = 'No date has been entered. Please enter a date';
}
});
There's an event onChange associated with datepicker. Is this what I should be using? If so, how do I specify that in my helper and what script changes do I need to make?
Try this,
$(document).on("change", "input[name=mydate]",function (){
var len = $(this).val().length;
var date = $(this).val();
var month = date.slice(0, 2);
var day = date.slice(3, 5);
var year = date.slice(6, 10);
alert("chkBirthday " + month);
if (month == '__') {
document.getElementById("MainContent_ErrorMessage").visibility = 'visible';
document.getElementById("MainContent_ErrorMessage").innerHTML = 'No date has been entered. Please enter a date';
}
});
Assuming you are using the popular JQuery UI's Datepicker, weirdly enough they are not entitled events but callbacks that can handle this event. See onSelect or onClose.
I am trying to validate date based on date entered in first textbox. If second textbox exceeds one year from the date entered in first textbox, then it should display an alert and blank the second date field textbox. Both the textboxes are readonly and gets the values from calender. I tried the below code but the alert is popping up even if the year is not more than a year. Also ,is it possible to pass 'name3' and 'name4' IDs as parameters. I need to apply this code to 10 rows.
<script>
function fixup()
{
var parts = document.getElementById('name3').value.split("-");
parts[2] = Number(parts[2]) + 1;
var pj = parts.join("-");
var x=document.getElementById('name4').value;
if(x>pj)
{
alert("Expiration date should not be greater than one year from start date");
document.getElementById('name4').value = "";
return false;
}
return true;
}
</script>
</head>
<body>
<form onsubmit="return fixup()">
<table>
<tr>
<td><input type="text" name="soname3" id="name3" size="15" readonly="readonly">
<img src="../Image/cal.gif" id="" style="cursor: pointer;" onclick="javascript:NewCssCal('name3','MMddyyyy','dropdown',false,'12')" /></td>
<td><input type="text" name="soname4" id="name4" size="15" readonly="readonly">
<img src="../Image/cal.gif" id="" style="cursor: pointer;" onclick="javascript:NewCssCal('name4','MMddyyyy','dropdown',false,'12'); " /> </td>
</tr>
</table>
<input type="submit" value="Submit">
</form>
I did Below code after suggestions by dm03514. but validation is not working..
function test()
{
start = document.getElementById('name3').value;
end = document.getElementById('name4').value;
compare(start, end);
}
function compare(sDate, eDate)
{
function parseDate(input) {
var parts = input.match(/(\d+)/g);
return new Date(parts[2], parts[0]-1, parts[1]); //parts[2] is year, parts[0] is month and parts[1] is date.
}
var parse_sDate = parseDate(sDate);
var parse_eDate = parseDate(eDate);
parse_sDate.setDate(parse_sDate.setFullYear(parse_sDate.getMonth() + 12));
if(parse_sDate>parse_eDate)
{
alert("End date should not be greater than one year from start date");
}
}
I would strongly recommend using a library like moment.js for handling dates. It has extensive date formatting and parsing features as well as comparison helpers:
var d1 = moment(document.getElementById('name3').value, 'YYYY-MM-DD');
var d2 = moment(document.getElementById('name4').value, 'YYYY-MM-DD');
var diff = d2.diff(d1, 'years');
if (diff > 0) {
alert("Expiration date should not be greater than one year from start date");
}
See also:Compare two dates in JS
Hi i have an app where user can select for start datetime and end datetime if they want to create an event.
Now this is an html where i use KendoUI datetime plugin:
<div class="demo-section" style="width: 535px;">
<label for="start">Start date:</label>
<input id="start" value="01/01/2013" />
<label for="end" style="margin-left:3em">End date:</label>
<input id="end" value="01/01/2013"/>
</div>
</li>
<script type="text/javascript">
$(document).ready(function(){
function startChange() {
var startDate = start.value();
if (startDate) {
startDate = new Date(startDate);
startDate.setDate(startDate.getDate());
end.min(startDate);
}
}
function endChange() {
var endDate = end.value();
if (endDate) {
endDate = new Date(endDate);
endDate.setDate(endDate.getDate());
start.max(endDate);
}
}
var start = $("#start").kendoDateTimePicker({
change: startChange,
parseFormats: ["MM/dd/yyyy"]
}).data("kendoDateTimePicker");
var end = $("#end").kendoDateTimePicker({
change: endChange,
parseFormats: ["MM/dd/yyyy"]
}).data("kendoDateTimePicker");
start.max(end.value());
end.min(start.value());
});
Issues is i cant get validation as i want. Suppose user select From date the To date should display date which is greater that currently selected From date.My currrent code seems not works well. Thanks
Are you saying that you want to be able to select a From date greater than To, and that when you do To should automatically update to be greater than From?
If so you're almost there. You just need to update the startChange function to update the To date relative to From.
function startChange() {
var startDate = start.value();
if (startDate) {
startDate = new Date(startDate);
startDate.setDate(startDate.getDate());
end.min(startDate);
var endDate = end.value();
if (endDate && endDate <= startDate) {
endDate.setDate(startDate.getDate() + 1);
end.value(endDate);
}
}
}
Check this jsFiddle for a full working example.