Loop from startdate to enddate from inputs with javascript - javascript

I've got a startdate and enddate from inputs. And I need to put all the dates from the startdate until the enddate into the database. Therefore I need to make a loop like this:
FOR i = startdate; i <= enddate; i + 1 day
{
here i use the date
}
How do I make such a loop with dates from input boxes?
I get 'invalid date' if I try to do this:
var endDate = new Date($("#enddate").val());
And I can't use the endDate.getTime() like I need as you said in the answer, if I do it like this.
var endDate = $("#enddate").val());
var endDateTime = endDate.getTime();
So basically: How can I convert the input to a date? The input of enddate is like this: dd/mm/yyyy.
No it's not an SQL question, I need to do this is javascript because I need to check the dates first.
Thank you for helping me out ;)

Would a loop like this work?:
var current_date = new Date("01/13/2013");
var end_date = new Date("01/20/2013");
var end_date_time = end_date.getTime();
while (current_date.getTime() < end_date_time) {
console.log(current_date);
current_date.setDate(current_date.getDate()+1);
}
http://jsfiddle.net/Sn6Ws/
Depending on the format of your textboxes' values, you can set it up like this:
$(document).ready(function () {
$("#btn").on("click", function () {
dateLooper(function (cur, end) {
console.log("Current date: " + cur.toString() + ", End Date: " + end.toString());
});
});
});
function dateLooper(callback) {
var start_date_text = document.getElementById("start_date").value;
var end_date_text = document.getElementById("end_date").value;
var current_date = new Date(start_date_text);
var end_date = new Date(end_date_text);
var end_date_time = end_date.getTime();
while (current_date.getTime() < end_date_time) {
//console.log(current_date);
callback.call(this, current_date, end_date);
current_date.setDate(current_date.getDate()+1);
}
}
http://jsfiddle.net/Sn6Ws/1/
Per your comments that explain the date are in the format "dd/mm/yyyy", you could use something like this:
var start_date_text = document.getElementById("start_date").value;
var start_split = start_date_text.split("/");
if (start_split.length != 3) {
return false;
}
start_date_text = start_split[1] + "/" + start_split[0] + "/" + start_split[2];
var end_date_text = document.getElementById("end_date").value;
var end_split = end_date_text.split("/");
if (end_split.length != 3) {
return false;
}
end_date_text = end_split[1] + "/" + end_split[0] + "/" + end_split[2];
to get the dates in the right format before passing them to new Date. Here's an updated jsFiddle that demonstrates it:
http://jsfiddle.net/Sn6Ws/4/
Of course, be careful that if the dates don't come in with the specified format (in case users can type this in or something), the code will most likely throw an error. You can obviously put more checks in to make sure certain things set before proceeding with certain operations (like making sure each item is a number/integer, making sure the days are in the range 1 to 31, etc.). So for that reason, you may want to go the route of regular expressions. At least with regular expressions, you can specify a specific pattern and know whether it matches perfectly or not, and immediately get the values you need to build a date.
Using regular expressions, here's an example that isn't complete but should hopefully help:
function dateLooper(callback) {
var re = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
var start_date_text = document.getElementById("start_date").value;
var start_match = re.exec(start_date_text);
if (start_match) {
var valid = true;
// Set `valid` variable based on the following
// Validate start_match[1] is valid day
// Validate start_match[2] is valid month
// Validate start_match[3] is valid year
if (valid) {
start_date_text = combineDate(start_match);
} else {
return false;
}
} else {
return false;
}
var end_date_text = document.getElementById("end_date").value;
var end_match = re.exec(end_date_text);
if (end_match) {
var valid = true;
// Set `valid` variable based on the following
// Validate end_match[1] is valid day
// Validate end_match[2] is valid month
// Validate end_match[3] is valid year
if (valid) {
end_date_text = combineDate(end_match);
} else {
return false;
}
} else {
return false;
}
var current_date = new Date(start_date_text);
var end_date = new Date(end_date_text);
var end_date_time = end_date.getTime();
var days_spent = 0;
while (current_date.getTime() < end_date_time) {
days_spent++;
callback.call(this, current_date, end_date, days_spent);
current_date.setDate(current_date.getDate()+1);
}
return days_spent;
}
function combineDate(re_match) {
return re_match[2] + "/" + re_match[1] + "/" + re_match[3];
}
http://jsfiddle.net/Sn6Ws/6/

Related

Im having trouble with Month comparison in JS

I am trying to compare months from a form, which are 1,2,3,4,5,6,7,8,9,10,11,12 to getMonth()
I have been trying to figure it out for a while, and tried parsing to Int and making sure the Int's
are the same, i.e. single digits, but to no effect.
function checkCard() {
var cardYearError = document.getElementById("cardYearError");
var monthError = document.getElementById("cardMonthError");
var date = new Date();
var month = parseInt(date.getMonth()+1);
var cardMonth = parseInt(document.getElementById("cardmonth"));
var year = parseInt(date.getFullYear());
var cardYear = parseInt(document.getElementById("cardyear"));
if (year > cardYear) {
cardYearError.innerHTML="Sorry your card has expired :1";
cardYear.focus();
cardYearError.style.color="red";
return false;
}
cardYearError.innerHTML="";
if ( year === cardYear && cardMonth < month) {
monthError.innerHTML="Sorry your card has expired :2";
cardMonth.focus();
monthError.style.color="red";
return false;
}
cardMonthError.innerHTML="";
return;
}
The year comparison works fine, but the second if statement will not work for some reason unknown to me.
you need to check year, cardYear, cardMonth & month first !
for this you have to log all these variables.
and you did not get the value of these two given lines
var cardMonth = parseInt(document.getElementById("cardmonth").value));
var cardYear = parseInt(document.getElementById("cardyear").value));
now you can try this code and let me if its work fine.
function checkCard() {
var cardYearError = document.getElementById("cardYearError");
var monthError = document.getElementById("cardMonthError");
var date = new Date();
var month = parseInt(date.getMonth()+1);
var cardMonth = parseInt(document.getElementById("cardmonth").value));
var year = parseInt(date.getFullYear());
var cardYear = parseInt(document.getElementById("cardyear").value));
if (year > cardYear) {
cardYearError.innerHTML="Sorry your card has expired :1";
cardYear.focus();
cardYearError.style.color="red";
return false;
}
cardYearError.innerHTML="";
console.log(`${year} === ${cardYear} && ${cardMonth} < ${month}`)
if ( year === cardYear && cardMonth < month) {
monthError.innerHTML="Sorry your card has expired :2";
cardMonth.focus();
monthError.style.color="red";
return false;
}
cardMonthError.innerHTML="";
return;
}
I fixed it by changing the html value properties. It was reading the value and not what was between the tags as I had thought.
I tried using this:
var demo = document.getElementById("demo");
demo.innerHTML=month+" "+cardMonth+" "+year+" "+cardYear;
To print the values and troubleshooted as I don't have breakpoints in notepad++.
Thanks for giving me the idea.

How to get specific year from the Date field in jquery

I know its a bit silly question, but I actually wanted to know how can I retrieve the year value for a date that I already have without using the "Split" function. I can achieve it with the help of the "split" function. Below is the code that I used in jquery.
outputJSon = JSON.parse($('#' + Datepicker_id).val());
var currentYear = parseInt(CalculateYearfromString($('#' + currentActivityCalendarId).parents('.service-timeline').find('.membership-year .period').text()));
if (currentYear === undefined && $.trim(currentYear) === "")
currentYear = new Date().getFullYear();
if (parseInt(outputJSon["Date"].split('/')[0]) === currentYear)
outputDate = outputJSon["Date"];
else
outputDate = outputJSon["Date"].replace(outputJSon["Date"].split('/')[0], currentYear)
outputDateType = outputJSon["DateType"];
In the above code, I am retrieving the date value in a JSON format which returns Date eg. 2016/05/26 and DateType eg. Day.
I am fetching the current year that I have selected and then checking if currentYear value is equal to the year that I have in the outputJSon["Date"]. If there is a match, then I am replacing the [0] value of the outputJSon["Date"] with the currentYear, with the help of replace function. This works as expected and no error is encountered.
I just want to be sure that if the date format changes(from 2016/05/26 to 26/05/2016)**then the split function that I have written will retrieve wrong value. How can I avoid this. Shall I remove **split function and think of something else?
Any help is appreciated.
Thanks,
Totally unsexy, but what's wrong with indexOf?
if (outputJSon["Date"].indexOf(currentYear) != -1) {
// currentYear is in the string somewhere
}
Note also that in the original, there is no need for parseInt:
outputJSon["Date"].split('/')[0] == currentYear
is sufficient (and less to type).
Also, parseInt will never return undefined, so:
currentYear === undefined
will always be false and so:
if (currentYear === undefined && $.trim(currentYear) === "")
will never be true and the assignment:
currentYear = new Date().getFullYear();
will never execute.
I would also seriously question the use of:
outputJSon = JSON.parse($('#' + Datepicker_id).val());
The use of JSON.parse seems entirely gratuitous, you already have a string returned by $('#' + Datepicker_id).val().
You can check the length to make sure it is a valid year number.
currentYear2 = outputJSon["Date"].split('/');
currentYear2 = (currentYear2[0].length === 4) ? currentYear2[0] : currentYear2[2];
Is there any issues when you simply do
outputDate = new Date(outputJSon["Date"]).getFullYear();
You can try something like this:
JSFiddle.
Code
function getYear() {
var input = $("#dpDate").val();
var cdate = getDate(input);
console.log(cdate, cdate.getFullYear());
}
function getDate(input) {
var arr = [];
var seperator = ['/', '-'];
var year, month, date;
var yearIndex = 2;
var result = undefined;
seperator.forEach(function(s) {
if (input.indexOf(s) > -1)
arr = input.split(s);
});
if (arr.length > 1) {
// Set year
if (arr[0] > 1000) {
year = arr[0]
yearIndex = 0;
} else if (arr[2] > 1000) {
year = arr[2];
yearIndex = 2;
}
// set month and date
// If string starts with year, assume yyyy/mm/dd
if (yearIndex === 0) {
month = arr[1]
date = arr[2]
} else {
// If value greater than 12, assume it as date and other one as month
if (arr[0] > 12) {
date = arr[0]
month = arr[1]
} else if (arr[1] > 12) {
date = arr[1]
month = arr[0]
}
// If none of the value is ggreater than 12, assume default format of dd/mm/yyyy
else {
date = arr[0]
month = arr[1]
}
}
result = new Date(year, month - 1, date);
}
return result;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input id="dpDate" type="text" placeholder="dd/mm/yyyy" value="15/2/2016" />
<button onclick="getYear()">Get Year</button>
regex_yearfirst = /\d{4}\W/;
regex_yearlast = /\d{4}\n/;
if (regex_yearfirst.test(outputJSon["Date"])) {
yearIndex=0;
}
else if (regex_yearlast.test(outputJSon["Date"])) {
yearIndex=2;
}
else {
console.log("date format not recognized")
}
if (parseInt(outputJSon["Date"].split('/')[yearIndex]) === currentYear) {
outputDate = outputJSon["Date"];
}
else {
outputDate = outputJSon["Date"].replace(outputJSon["Date"].split('/')[yearIndex], currentYear)
}

Insert more than 250 items in sharepoint list using javascript

I am not able to add 365 days( date format: 01/01/2014) of year in a sharepoint list using javascript.
but it is updating list when I enter range of 'for' loop = 250.
Please refer below code.
function DateIncrement() {
var siteUrl = '/sites/..';
var clientContext = new SP.ClientContext(siteUrl);
var oList = clientContext.get_web().get_lists().getByTitle('Student');
var itemCreateInfo = new SP.ListItemCreationInformation();
for (i = 1; i < 365; i++) {
var myDate = new Date("01/01/2014");
myDate.setDate(myDate.getDate() + i);
var str = myDate;
this.oListItem = oList.addItem(itemCreateInfo);
oListItem.set_item('Date', str);
oListItem.update();
}
clientContext.load(oListItem);
clientContext.executeQueryAsync(onSucceededCallback, onFailedCallback);
function onSucceededCallback(sender, args) {
alert("Complete");
}
function onFailedCallback(sender, args) {
alert("Failed");
}
}
The date must be specially formatted. In SharepointPlus I created a function that converts a JavaScript Date to the Sharepoint format.
The format should be: "year-month-day hours:minutes:seconds". So, for "31/Oct/2012" it must be "2012-10-31 00:00:00".
The function toSPDate looks like that:
function toSPDate(oDate) {
var pad = function(p_str){
if(p_str.toString().length==1){p_str = '0' + p_str;}
return p_str;
};
var month = pad(oDate.getMonth()+1);
var day = pad(oDate.getDate());
var year = oDate.getFullYear();
var hours = pad(oDate.getHours());
var minutes = pad(oDate.getMinutes());
var seconds = pad(oDate.getSeconds());
return year+"-"+month+"-"+day+" "+hours+":"+minutes+":"+seconds;
}
Note: SharepointPlus uses the Sharepoint web services. I'm not sure if you need to do the same with the Microsoft native functions.
Note 2: I read again your question but I'm not sure I understood correctly... If not, please try to explain again your issue.

Get the next highest date value after excluding values from an array

I have a myDate variable with the value 18-Nov-2013.Each day its value is being changed.Tommorow this myDate variable will have the value 19-Nov-2013.I have a list of values that i have mapped into a single array named exclude which contains some dates that are to be excluded ,now it has values ["20-Nov-2013",21-Nov-2013", "23-Nov-2010"] .How could i filter my value from the list of values from the exclude array.I need the next highest value from the array.So here i need the value 22-Nov-2013 after tommorrows date.Could someone help me with this.
var excluded = ["30-Nov-2013","01-Dec-2013","02-Dec-2013"];
var myDate = "29-Nov-2013";
var month = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var current = new Date(myDate);
while(true){
current = new Date((current.getDate()+1<10? "0"+(current.getDate()+1):(current.getDate()+1))+ "-" + month[current.getMonth()] + "-" + current.getFullYear());
var checkDate = (current.getDate()<10? "0"+(current.getDate()):(current.getDate()))+ "-" + month[current.getMonth()] + "-" + current.getFullYear();//this is necessary for when the +1 on day of month passes the month barrier
if(-1 == excluded.indexOf(checkDate))
break;
}
alert(checkDate);
I don't know if this is the best approach, or if is the best algorithm, but you may try this:
var myDate = ["17-Nov-2013", "18-Nov-2013"];
var excluded = ["20-Nov-2013", "21-Nov-2013", "23-Nov-2013"];
var months = {"Nov": 10}; // Add others months "Jan": 1, "Fev": 2 etc...
function findExcluded(date)
{
for (var i = 0; i < excluded.length; i++)
{
if (excluded[i] === date)
{
return true;
}
}
return false;
}
function nextDate()
{
var last = myDate[(myDate.length - 1)];
var s = last.split("-");
var d = new Date(s[2], months[s[1]], s[0]);
var next = new Date(d);
var chkDate = "";
do
{
next.setDate(next.getDate() + 1);
chkDate = next.getDate() + "-" + findMonth(next.getMonth()) + "-" + next.getFullYear();
} while(findExcluded(chkDate));
return chkDate;
}
function findMonth(m)
{
var i = 10; // When you fill all months on 'months' array, this variable should start at '0' in order to loop to works.
for (var month in months)
{
if (i == m)
{
return month;
}
i++;
}
}
var nd = nextDate();
alert(nd);
See it woring here.
No code ? Well here will be my method:
1.Get next date for mydate. Say that is var nextDate.
2.Check whether that date exist in the array.
3.If exists add one more day to nextDate. Again check in the array.
4.Do it until you get a date which is not present in your exclude array
For checking whether it exists in the array you can use arrValues.indexOf(nextDateInProperFormat) > -1

How to compare two different dates in dd/mm/yyyy format

Can anyone help me in finding the solution
i just want to compare two dates in dd/mm/yyyy format.
function compareDate(dt1 , dt2 , formatString){var returnVal = 2;
var dt1Parts;
var dt2Parts;
var dt1dd;
var dt1mm;
var dt1yyyy;
var dt2dd;
var dt2mm;
var dt2yyyy;
if(formatString == 'dd/mm/yyyy'){
dt1Parts = dt1.split('/');
dt2Parts = dt2.split('/');
dt1dd = parseInt(dt1Parts[0]);
dt1mm = parseInt(dt1Parts[1]);
dt1yyyy = parseInt(dt1Parts[2]);
dt2dd = parseInt(dt2Parts[0]);
dt2mm = parseInt(dt2Parts[1]);
dt2yyyy = parseInt(dt2Parts[2]);
}
else if(formatString == 'dd-mm-yyyy'){
dt1Parts = dt1.split('-');
dt2Parts = dt2.split('-');
dt1dd = parseInt(dt1Parts[0]);
dt1mm = parseInt(dt1Parts[1]);
dt1yyyy = parseInt(dt1Parts[2]);
dt2dd = parseInt(dt2Parts[0]);
dt2mm = parseInt(dt2Parts[1]);
dt2yyyy = parseInt(dt2Parts[2]);
}else{
alert(formatString+' format is not supported.');
}
if(dt1yyyy == dt2yyyy && dt1mm == dt2mm && dt1dd == dt2dd){
returnVal = 0;
}
else if(dt1yyyy > dt2yyyy){
returnVal = 1 ;
}else if(dt1yyyy == dt2yyyy ){
if(dt1mm > dt2mm){
returnVal = 1;
}else if(dt1mm == dt2mm){
if(dt1dd > dt2dd){
returnVal = 1;
}else{
returnVal = -1;
}
}else{
returnVal = -1;
}
}else{
returnVal = -1;
}
return returnVal;
}
Thanks in advance,
Shilpa
Invert the strings to yyyy/mm/dd, or convert them to a number or Date object.
The simplest way just for comparison would be ASCII order. Invert using something like this:
function invert(date) {
return date.split(/[/-]/).reverse().join("")
}
function compareDates(date1, date2) {
return invert(date1).localeCompare(invert(date2));
}
Here's how you convert that string format to a date:
var myString = "17/07/1979",
correctFormat = myString.replace(/(\d+)\/(\d+)\/(\d+)/, "$3/$2/$1"),
myDate = new Date(correctFormat);
Without knowing what language or class libs you're working with:
Method 1: Resort your strings to be yyyymmdd and the do string compare.
Method 2: Stuff yyyy mm and dd into the high, middle, and low bits of an integer and compare.
The easiest way is probably to create 2 javascript Date objects from your input string. You could achieve that by chopping your input into day, month and year. You can use the 'substring' function for that.
Then you can do:
var firstDate = new Date(year1, month1, day1);
var secondDate = new Date(year2, month2, day2);
Once you have 2 date objects, you can use the normal compare operators:
if (firstDate > secondDate)
// do something
else
...
Try this
var date1=new Date('your date1 string');
var date2=new Date('your date2 string');
var difference=new Date(date1.getTime()-date2.getTime());
if ($.datepicker.parseDate('dd/mm/yy', fDate) > $.datepicker.parseDate('dd/mm/yy', tDate)) {
//do something
}
You can compare two dates.Here I compare from date greater than to date
try this

Categories

Resources