So I am trying to find if a certain date is between two other dates and then display the correct div text. I have it working to a point, but it doesn't seem to work checking multiple divs. Heres what I have below, basically it uses the 'date-selected' div and runs through each 'date' div to find the date match.
It seems to work if the date is 02/01/2019, but if I set the date to 02/01/2020 it will not find the correct div, which should be 02/01/2020-01/01/2021. Does anyone know what the problem is?
// on click
$(".check").click(function() {
// foreach date div
$(".date").each(function() {
var firstdate = $(this).text().split('-')[0];
var lastdate = $(this).text().split('-')[1];
var fDate, lDate, cDate;
fDate = new Date(firstdate); // firstdate
lDate = new Date();
lDate.setDate(lDate.getDate(lastdate)); // lastdate
cDate = new Date($('.date-selected').text()); // date to check if between
if (Date.parse(cDate) <= Date.parse(lDate) && Date.parse(cDate) >= Date.parse(fDate)) {
// output matched date
$('.correct-date').text('Date between: ' + $(this).text());
return true;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="date-selected">02/01/2020</div>
<div class="date">01/01/2019-01/01/2020</div>
<div class="date">02/01/2020-01/01/2021</div>
<div class="correct-date"></div>
<button class="check">check</button>
not need to new Date,
only use Date.parse:
$(".check").click(function() {
// foreach date div
$(".date").each(function() {
if (
dateCheck(
$(this).text().split('-')[0],
$(this).text().split('-')[1],
$('.date-selected').text()
)
) {
// output matched date
$('.correct-date').text('Date between: ' + $(this).text());
return true;
}
});
});
function dateCheck(from,to,check) {
var fDate,lDate,cDate;
fDate = Date.parse(from);
lDate = Date.parse(to);
cDate = Date.parse(check);
if((cDate <= lDate && cDate >= fDate)) {
return true;
}
return false;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="date-selected">02/01/2020</div>
<div class="date">01/01/2019-01/01/2020</div>
<div class="date">02/01/2020-01/01/2021</div>
<div class="correct-date"></div>
<button class="check">check</button>
You can use getTime() for compare date:
// on click
$(".check").click(function() {
// foreach date div
$(".date").each(function() {
var firstdate = $(this).text().split('-')[0];
var lastdate = $(this).text().split('-')[1];
var fDate, lDate, cDate;
fDate = new Date(firstdate); // firstdate
lDate = new Date(lastdate);
//lDate.setDate(lDate.getDate(lastdate)); // lastdate
cDate = new Date($('.date-selected').text()); // date to check if between
if (cDate.getTime() <= lDate.getTime() && cDate.getTime() >= fDate.getTime()) {
// output matched date
$('.correct-date').text('Date between: ' + $(this).text());
return true;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="date-selected">02/01/2020</div>
<div class="date">01/01/2019-01/01/2020</div>
<div class="date">02/01/2020-01/01/2021</div>
<div class="correct-date"></div>
<button class="check">check</button>
Related
every day add the value in the div with + 1 a type of counter
...
var i = 1;
$(".teste").each(function () {
i = parseFloat(i) + parseFloat($(this).data("teste"));
});
$(".teste").html(i);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="teste" data-teste="2" id="teste"> </div>
If you want to increment i by 1 every day you will need some kind of loop and check against the date to see if the day has changed.
var i = parseInt($(this).data("teste")) + 1;
var running = true;
var currentDate = new Date();
while (running == true)
{
if (currentDate.toDateString() != (new Date()).toDateString())
{
i = parseInt(i) + parseInt($(this).data("teste"));
$(".teste").html(i);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="teste" data-teste="2" id="teste"> </div>
I have a textbox which allows users to choose a date from a calendar in mm/dd/yyyy format. I used the pikaday and moment libraries to achieve this. Now, if the user selects a date that is not in the future, I want to show an error in a label saying that the date is invalid. What is the 'best' way to achieve this? Working with dates in Javascript turned out to be quite a headache.I have provided my current approach:
textbox:
<asp:TextBox ID="txtDepartureDate" runat="server" ForeColor="Gray" onfocus="txtOnFocusDeparture(this)" onblur="txtOnBlurDeparture(this)" oninput="oninputDeparture()" AutoPostBack="True">DEPARTURE DATE</asp:TextBox>
script:
<script type="text/javascript">
function oninputDeparture() {
var inputDate = moment(document.getElementById('txtDepartureDate').value, 'DD/MM/YYYY');
var todayDate = moment().format('DD/MM/YYYY');
var lblError = document.getElementById('lblError');
var daysDiff = todayDate.diff(inputDate, 'days');
if (daysDiff <= 0) {
lblError.innerText = "Departure Day should be after today";
}
else {
lblError.innerText = "";
}
}
</script>
var todayDate = moment().format('DD/MM/YYYY');
var lblError = document.getElementById('lblError');
var daysDiff = todayDate.diff(inputDate, 'days');
moment.diff requires a moment object. todayDate is assigned as string in this case.
Also consider quick exit when the user is still typing
Have a look at the example.
var dateInput = document.getElementById('txtDepartureDate');
var lblError = document.getElementById('lblError');
function setError(text) {
lblError.innerText = text
}
function oninputDeparture() {
var value = dateInput.value;
var dateValue = moment(value, 'DD/MM/YYYY');
if (value.length < 10 || !dateValue.isValid()) {
return;
}
var todayDate = moment();
var daysDiff = todayDate.diff(dateValue, 'days');
if (daysDiff >= 0 && !dateValue.isAfter(todayDate, 'days')) {
setError("Departure Day should be after today");
} else {
setError("");
}
}
setTimeout(() => {
dateInput.value = moment().add(1, 'days').format('DD/MM/YYYY')
oninputDeparture()
}, 1000)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script>
<input id="txtDepartureDate" type="text" oninput="oninputDeparture()" />
<div id="lblError"></div>
I have this code which you can select date and get results according to it. Now in the place of months and years selection i want a button that shows previous month and another button that shows next month. Like that Next day and previous day. Can someone please help me with this code snippet.
1. Button one - Previous month
2. Button two - Next month
3. Button three - Previous Day
4. Button four - Next Day
All results should be on HTML page.
<HTML>
<HEAD>
<TITLE></TITLE>
<STYLE TYPE="text/css">
TD, TH {text-align:center}
</STYLE>
<SCRIPT LANGUAGE="JavaScript">
function getFirstDay(theYear, theMonth){
var firstDate = new Date(theYear,theMonth,1)
return firstDate.getDay()
}
function getMonthLen(theYear, theMonth) {
var oneDay = 1000 * 60 * 60 * 24
var thisMonth = new Date(theYear, theMonth, 1)
var nextMonth = new Date(theYear, theMonth + 1, 1)
var len = Math.ceil((nextMonth.getTime() -
thisMonth.getTime())/oneDay)
return len
}
var theMonths = ["January","February","March","April","May","June","July","August",
"September","October","November","December"]
function getObject(obj) {
var theObj
if (document.all) {
if (typeof obj == "string") {
return document.all(obj)
} else {
return obj.style
}
}
if (document.getElementById) {
if (typeof obj == "string") {
return document.getElementById(obj)
} else {
return obj.style
}
}
return null
}
function populateTable(form) {
var theMonth = form.chooseMonth.selectedIndex
var theYear = parseInt(form.chooseYear.options[form.chooseYear.selectedIndex].text)
// initialize date-dependent variables
var firstDay = getFirstDay(theYear, theMonth)
var howMany = getMonthLen(theYear, theMonth)
// fill in month/year in table header
getObject("tableHeader").innerHTML = theMonths[theMonth] +
" " + theYear
// initialize vars for table creation
var dayCounter = 1
var TBody = getObject("tableBody")
// clear any existing rows
while (TBody.rows.length > 0) {
TBody.deleteRow(0)
}
var newR, newC
var done=false
while (!done) {
// create new row at end
newR = TBody.insertRow(TBody.rows.length)
for (var i = 0; i < 7; i++) {
// create new cell at end of row
newC = newR.insertCell(newR.cells.length)
if (TBody.rows.length == 1 && i < firstDay) {
// no content for boxes before first day
newC.innerHTML = ""
continue
}
if (dayCounter == howMany) {
// no more rows after this one
done = true
}
// plug in date (or empty for boxes after last day)
newC.innerHTML = (dayCounter <= howMany) ?
dayCounter++ : ""
}
}
}
function fillYears() {
var today = new Date()
var thisYear = today.getFullYear()
var yearChooser = document.dateChooser.chooseYear
for (i = thisYear; i < thisYear + 5; i++) {
yearChooser.options[yearChooser.options.length] = new Option(i, i)
}
setCurrMonth(today)
}
// set month choice to current month
function setCurrMonth(today) {
document.dateChooser.chooseMonth.selectedIndex = today.getMonth()
}
</SCRIPT>
</HEAD>
<BODY onLoad="fillYears(); populateTable(document.dateChooser)">
<H1>Calender</H1>
<HR>
<TABLE style="width:100%;height:80%;" ID="calendarTable" BORDER=1 ALIGN="center">
<TR>
<TH ID="tableHeader" COLSPAN=7></TH>
</TR>
<TR><TH>Sun</TH><TH>Mon</TH><TH>Tue</TH><TH>Wed</TH>
<TH>Thu</TH><TH>Fri</TH><TH>Sat</TH></TR>
<TBODY ID="tableBody"></TBODY>
<TR>
<TD COLSPAN=7>
<P>
<FORM NAME="dateChooser">
<SELECT NAME="chooseMonth"
onChange="populateTable(this.form)">
<OPTION SELECTED>January<OPTION>February
<OPTION>March<OPTION>April<OPTION>May
<OPTION>June<OPTION>July<OPTION>August
<OPTION>September<OPTION>October
<OPTION>November<OPTION>December
</SELECT>
<SELECT NAME="chooseYear" onChange="populateTable(this.form)">
</SELECT>
</FORM>
</P></TD>
</TR>
</TABLE>
</BODY>
</HTML
I suggest to use moment.js. It helps alot when you work with time and date.
e.g. after pressing a button "next month" you can use moment().add(1, 'months') to add 1 month to your current date. you can store the date after switching e.g. on data attributes or hidden input or ...
complete documentation you can find on https://momentjs.com/docs/
I'm trying to make an alert to user when choose a date. For example, when user choose 2018-09-13, then the alert will show message "7 days later will be 2018-09-20". But instead, the alert message shows 2018-09-137.
<input type="date" name = "date" id = "date" onchange="javascript:var chooseDate=(this.value)+7; alert('7 days later will be '+chooseDate);" >
How should I add days into the date ?? please help, thank you.
this.value will return the date as string using the format YYYY-MM-DD, so if you "add" 7, it will be YYYY-MM-DD7. What you could do is create a new Date object, and then add the days you want, like this:
var chooseDate=new Date(this.value);
chooseDate.setDate(chooseDate.getDate()+7);
alert('7 days later will be '+chooseDate);
This will give you the complete date, though, which is something you probably don't want, so you would have to get the values you actually need, like this:
var chooseDate=new Date(this.value);
chooseDate.setDate(chooseDate.getUTCDate()+7);
var futureDate = chooseDate.getFullYear()+'-'+('0'+(chooseDate.getMonth()+1)).slice(-2)+'-'+('0'+(chooseDate.getDate())).slice(-2);
alert('7 days later will be '+chooseDate);
Here you have a working example:
<input type="date" name = "date" id = "date" onchange="var chooseDate=new Date(this.value);chooseDate.setDate(chooseDate.getUTCDate()+7);var futureDate=chooseDate.getFullYear()+'-'+('0'+(chooseDate.getMonth()+1)).slice(-2)+'-'+('0'+(chooseDate.getDate())).slice(-2);alert('7 days later will be '+futureDate);" >
How about this in :
addDays = function(input_date, days) {
var date = new Date(input_date);
date.setDate(date.getDate() + days);
return date;
}
You then call do addDays(this.value, 7) in onchange().
And, please reference on getDate() and setDate().
You are working with string instead of a date object:
function lPad(val) {
return ((10 > val ? '0' : '') + val);
}
function add(input, unit, value) {
var cur = input.value;
var byValue = Number(value);
if (!/^\d{4}\-\d{2}\-\d{2}$/.test(cur) || !/day|month|year/.test(unit) || isNaN(byValue)) {
console.warn('invalid parameters!');
return false;
}
var dt = new Date(cur.replace(/\-/g, '/'));
if (!dt || isNaN(dt)) {
console.warn('invalid date!');
return false;
}
if ('day' === unit) {
dt.setDate(dt.getDate() + byValue);
} else if ('month' === unit) {
dt.setMonth(dt.getMonth() + byValue);
} else {
dt.setFullYear(dt.getFullYear() + byValue);
}
input.value = [dt.getFullYear(), lPad(1 + dt.getMonth()), lPad(dt.getDate())].join('-');
console.log(cur, value, unit, '=', input.value);
return true;
}
<input type="date" onchange="add(this,'day','+7');" title="+7 days" />
<input type="date" onchange="add(this,'month','-1');" title="-1 month" />
<input type="date" onchange="add(this,'year','+2');" title="+2 year" />
try this one ...
<input type="date" name = "date" id = "date" onchange="ggrr(this)" >
<script>
function ggrr(input){
var dateString = input.value;
var myDate = new Date(dateString);
var d = new Date(Date.parse(myDate));
var y = d.getFullYear();
var da = d.getDate() + 7;
var m = d.getMonth();
console.log(y+':'+m+':'+da);
}
</script>
I want new date range in each box, but it return only last text-box date range. I also made text boxes id's dynamic but still I am facing this issues. I have start date and end date for each text box and I calculated date range in PHP for start date and end date and disabled all those dates which is selected by user in their start date and date all is working fine but it returns last textbox dates disabled in datepicker.
Here is the screenshot-
Sample Image
Javascript function for datepicker to disbaled dates for each box -
$(function () {
var count = $('#count').val();
var uid = $('#usersId').val();
var pid = $('#projectsId').val();
for (i = 1; i <= count; i++) {
$('#projectAssStartDate' + i).datepicker({
beforeShowDay: function (date) {
var dateString = jQuery.datepicker.formatDate('yy-mm-dd', date);
minDate: 0;
alert(dateRange);
console.log(dateString);
return [dateRange.indexOf(dateString) == -1];
}
});
var date_range = $('#calendarDateString' + i).val();
var newdate = date_range.replace(/,(?=[^,]*$)/, '');
var res = '"' + newdate + '"';
var startDate, endDate, dateRange = res;
$('#projectAssEndDate' + i).datepicker({
beforeShowDay: function (date) {
var dateString = jQuery.datepicker.formatDate('yy-mm-dd', date);
console.log(dateString);
return [dateRange.indexOf(dateString) == -1];
}
});
}
});
HTML for create boxes id's dynamic and fetch values from it.
<input type="text" class='datepicker' size='11' title='D-MMM-YYYY' name="projectAssStartDate[]" id="projectAssStartDate<?php echo $id;?>" value="" style="padding: 7px 8px 7px 8px;font-weight: bold;" />
<input type="text" class='datepicker' size='11' title='D-MMM-YYYY' name="projectAssEndDate[]" id="projectAssEndDate<?php echo $id;?>" value="" style="padding: 7px 8px 7px 8px;font-weight: bold;" />
<input id="calendarDateString<?php echo $id;?>" name="calendarDateString<?php echo $id;?>" title='D-MMM-YYYY' type="text" value="<?php echo $string;?>" />
<input id="projectsId" name="projectsId[]" type="hidden" value="<?php echo $rows['PROJECT_ID'];?>" />
<input id="usersId" name="usersId[]" type="hidden" value="<?php echo $rows['UM_ID'];?>" />
Please check the answer and reply whether this is the way you needed it to go. If not please comment what change you want with respect to this below code result. And I'm sorry that I have manipulated few of your values to ease my result. Will give details explanation if this is what you are expecting.
$(function () {
var count = 2;//$('#count').val();
var uid = $('#usersId').val();
var pid = $('#projectsId').val();
// populate the array
var startDatearray= ["index 0","2016-06-15","2016-06-20"]; // you dont need to create this array .. just fetch these dates from your database as u need
var endDatearray=["index 0","2016-06-21","2016-06-25"];
var i;
for (i = 1; i <= count; i++) {
$('#projectAssStartDate' + i).datepicker({
beforeShowDay: function (date) {
var i=parseInt($(this).attr('id').replace(/[^0-9\.]/g, ''), 10); // as i wont get here so i took it from the current id
var startDate = startDatearray[i], // some start date
endDate = endDatearray[i]; // some end date
var dateRange = [];
for (var d = new Date(startDate); d <= new Date(endDate); d.setDate(d.getDate() + 1)) {
dateRange.push($.datepicker.formatDate('yy-mm-dd', d));
}
var dateString = jQuery.datepicker.formatDate('yy-mm-dd', date);
minDate: 0;
//alert(date);
console.log(dateString +"__"+[dateRange.indexOf(dateString) == -1] +"__"+dateRange);
return [dateRange.indexOf(dateString) != -1]; // if u need the opposit then you can use { == -1}
}
});
var date_range = $('#calendarDateString' + i).val();
var newdate = date_range.replace(/,(?=[^,]*$)/, '');
var res = '"' + newdate + '"';
var startDate, endDate, dateRange = res;
$('#projectAssEndDate' + i).datepicker({
beforeShowDay: function (date) {
var dateString = jQuery.datepicker.formatDate('yy-mm-dd', date);
console.log(dateString);
var i=parseInt($(this).attr('id').replace(/[^0-9\.]/g, ''), 10); // as i wont get here so i took it from the current id
var startDate = startDatearray[i], // some start date
endDate = endDatearray[i]; // some end date
var dateRange = [];
for (var d = new Date(startDate); d <= new Date(endDate); d.setDate(d.getDate() + 1)) {
dateRange.push($.datepicker.formatDate('yy-mm-dd', d));
}
var dateString = jQuery.datepicker.formatDate('yy-mm-dd', date);
minDate: 0;
//alert(date);
console.log(dateString +"__"+[dateRange.indexOf(dateString) == -1] +"__"+dateRange);
return [dateRange.indexOf(dateString) != -1]; // if u need the opposit then you can use { == -1}
}
});
}
});