Date range for cash flows - javascript

I am trying to create a cash flow with dates.
I have 2 dates: Start and End
If payments are monthly and suppose the rent payment day is on 15th. Then the cashflow would :
10/15/2018
11/15/2018
12/15/2018
1/15/2019..... and so forth until the end date.
Similarly if rent is paid every 3 months then cashflow would look like:
10/15/2018 1/15/2018 4/15/2018... and so forth.
I have the following code which works every time except when the rent is on 1st day of the month or last day of the month.
function createLedger(stDate, etDate){
if (stDate && etDate) {
var d2 = new Date(etDate);
var sDay = d2.getUTCDate();
var sMonth = d2.getUTCMonth() + 1;
var sYear = d2.getUTCFullYear();
var endOfLeaseDate = sYear + "-" + sMonth + "-" + sDay;
var d3 = new Date(stDate);
var s1Day = d3.getUTCDate();
var s1Month = d3.getUTCMonth() + 1;
var s1Year = d3.getUTCFullYear();
var startOfLeaseDate = s1Year + "-" + s1Month + "-" + s1Day;
var ddlFrequency = document.getElementById("ddFrequency");
var selectedFrequency = ddlFrequency.options[ddlFrequency.selectedIndex].value;
if (selectedFrequency) {
if (selectedFrequency == "D") {
dates = dateRange(startOfLeaseDate, endOfLeaseDate);
}
Here is where the issue is:
else if (selectedFrequency == "Q") {
dates = getQuartersDateRange(d3, d2)
dates = SortedQuarter(d3,dates);
}
else {
dates = [];
}
}
else {
dates = [];
}
createFormElement();
}
}
And i have the following codes to get the date range and quarter range.
function getQuartersDateRange(startOfLeaseDate, endOfLeaseDate) {
var dates = [];
var qlist = listQuarters(startOfLeaseDate, endOfLeaseDate);
for (var i = 0; i < qlist.length; i++) {
var yearquarter = qlist[i].split('-');
var dateQ = new Date(yearquarter[0], (yearquarter[1] * 3 - 3) + 1, startOfLeaseDate.getUTCDate());
qDay = dateQ.getUTCDate();
qMonth = dateQ.getUTCMonth();
qYear = dateQ.getUTCFullYear();
var qDate = qYear + "-" + qMonth + "-" + qDay;
dates.push(qDate);
}
return dates;
}
function SortedQuarter(startOfLeaseDate, dates) {
var qdatesSorted = [];
for (var j = 0; j < dates.length; j++) {
var month;
var splitDate = dates[j].split('-');
if (j == 0)
month = startOfLeaseDate.getUTCMonth() + 1;
else {
startOfLeaseDate.setMonth(startOfLeaseDate.getUTCMonth() + 3)
month = startOfLeaseDate.getUTCMonth() + 1;
}
var qDate = splitDate[0] + "-" + month + "-" + splitDate[2];
qdatesSorted.push(qDate);
}
return qdatesSorted;
}
function listQuarters(sDate, eDate) {
if (sDate > eDate) {
var t = eDate;
eDate = sDate;
sDate = t;
}
sDate = new Date(sDate);
sDate.setDate(2);
var startQ = getQuarter(sDate);
var endQ = getQuarter(eDate);
var result = [startQ];
while (startQ != endQ) {
sDate.setMonth(sDate.getUTCMonth() + 3);
startQ = getQuarter(sDate);
result.push(startQ);
}
return result;
}
The issue here is that when the start date = 11/1/2018 and end date = 01/31/2020
the cashflow prints as follows
11/1/2018 3/1/2019 6/1/2019 9/1/2019 12/1/2019...and so forth. So instead of going from 11/1/2018 to 2/1/2018, it skips the month and goes to the next one. I am not sure why it does that only towards the end of the month or the beginning of the month.
Any help is appreciated. Thank you.

Using moment library worked for me. aLSO, I rewrote the date range as follows:
function createLedger(stDate, etDate) {
if (stDate && etDate) {
var endOfLeaseDate = moment(etDate, "MM/DD/YYYY");
var startOfLeaseDate = moment(stDate, "MM/DD/YYYY");
dateRange(startOfLeaseDate, endOfLeaseDate);
}
}
function dateRange(stDate, etDate) {
var dates = [];
var now = etDate.clone();
var day = etDate.date();
while(now.isAfter(stDate)) {
var month = now.clone().endOf("month");
if (now.date() < day && day <= month.date()) {
now.date(day);
}
dates.push(now.format("MM/DD/YYYY"));
//dates._reverse();
now = now.clone().subtract({"months": 1});
}
console.log(dates);
}
function RunLedgerAndPV() {
var stDate = "11/26/2018";
var etDate = "09/25/2019";
createLedger(stDate, etDate);
}
RunLedgerAndPV();

Related

mutliple set timeouts running at once

so, i have a for loop that I want to run multiple set timeouts at once so it can continually check if it is a certain time for multiple times. i can't just check for all multiple times all at once, the check needs to repeat after different amounts of time. it only continues to repeat the last iteration of the loop, the last dict in lat.
my approach simplified a bit:
lat = list of dictionaries with some values that differentiate them + times
for(i = 0; i< lat.length; i++){
if(lat[i][differentiate value]) = {
function checktime(){
if(currenttime != lat[i]){
setTimeout(checktime,30000)
}
else{
console.log("yay the time is right!")
}
}
else if(lat[i][differentiate value]) = {
function checktime(){
if(currenttime != lat[i]){
setTimeout(checktime,50000)
}
else{
console.log("yay the time is right!")
}
}
}
How would I go about making this (its for a notification app)
original code:
(each value in later looks like [[75,null,[7,28,2021]], null,[[9,52,"p"]],"e&r"] with the amount of notifications, a preset date, the date for these reminders to be on, by time, which would be the first if, and the array of at times. for testing I had 2 laters with 2 different at times):
chrome.storage.sync.get('later', function(data){
if (data.later !== null){
var lat = data.later;
for(i = 0; i< lat.length; i++){
var currentDict = lat[i];
if(currentDict['notis'][1] !== null){
console.log("cheese")
var by = currentDict['notis'][1];
console.log(by)
const d = new Date();
var hr = d.getHours();
var min = d.getMinutes();
var sec = d.getSeconds();
var da = currentDict['notis'][0][2][1];
var mo = currentDict['notis'][0][2][0];
var ye = currentDict['notis'][0][2][2]
var h = by[0];
var m = by[1];
var ampm = by[2];
if(ampm == "p"){
h = h + 12;
}
var byMS = h*3600000 + m*60000;
var currentMS = hr*3600000 + min*60000 + sec*1000;
//check if right date then check if time is lesss than
function checkdate(){
var day = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
if(da == day && mo == month && ye == year){
var amt = 0;
function checktime(){
if(byMS >= currentMS){
//noti and delete
var int = setInterval(function(){
chrome.notifications.create({
title: currentDict['name'],
message: "do da " + currentDict['name'],
iconUrl: "logo.png",
type: "basic"
})
amt++
console.log(amt)
const dddd = new Date();
console.log(dddd.getMinutes() + " / " + dddd.getSeconds())
if(amt >= currentDict['notis'][0][0]){
clearInterval(int)
console.log("done")
//ju finish taht
console.log(lat)
lat.splice(lat.indexOf(currentDict),1)
console.log(lat)
chrome.storage.sync.set({'later': lat})
}
}, (byMS-currentMS)/currentDict['notis'][0][0])
}
else{
setTimeout(checktime,30000)
}
}
checktime();
}
else{
setTimeout(checkdate,66400000)
}
}
checkdate();
}
else if(currentDict['notis'][2] !== null){
console.log("cheese")
var at = currentDict['notis'][2];
console.log(at)
var arrayat = [];
for(j = 0; j<= at.length-1; j++){
var atcycle = at[j];
console.log(atcycle)
const ddd = new Date();
var hr = ddd.getHours();
var min = ddd.getMinutes();
var da = currentDict['notis'][0][2][1];
var mo = currentDict['notis'][0][2][0];
var ye = currentDict['notis'][0][2][2]
var hrat = atcycle[0];
var minat = atcycle[1];
var ampm = atcycle[2];
if(ampm == "p"){
hrat = hrat + 12;
}
console.log(hrat + "/" + minat + "/" + ampm)
if(hr <= hrat){
var temparray = [];
temparray.push(hrat)
temparray.push(minat)
arrayat.push(temparray);
console.log(arrayat)
}
else if(hr == hrat){
if(min<minat){
var temparray = [];
temparray.push(hrat)
temparray.push(minat)
arrayat.push(temparray);
console.log(arrayat)}
}
}
console.log(arrayat.length)
function checkdate(){
console.log(arrayat.length)
console.log("date")
const d = new Date();
var day = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
if(da == day && mo == month && ye == year){
function check(){
console.log(arrayat.length)
console.log("check")
for(l=0; l<arrayat.length; l++){
console.log(arrayat.length)
const dd = new Date();
var hr = dd.getHours();
var min = dd.getMinutes();
console.log(arrayat[l][1])
console.log(min)
if(arrayat[l][0] == hr && arrayat[l][1] == min ){ //at one of the times
console.log(arrayat)
arrayat.splice(l,1)
console.log(arrayat)
if(arrayat.length == 0){
lat.splice(lat.indexOf(currentDict),1)
chrome.storage.sync.set({'later': lat})
console.log(lat)
}
chrome.notifications.create({
title: currentDict['name'],
message: "do da " + currentDict['name'],
iconUrl: "logo.png",
type: "basic"
})
//add noti with name and delete it
console.log(arrayat)
check();
}
}
console.log(arrayat.length)
if(arrayat.length !== 0){
console.log("and repeat")
setTimeout(check,15000);//SETINTERVAL INSTEAD? ANDCLEAR
}
}
check();
}
else{
setTimeout(checkdate,66400000)
}
}
checkdate();
}
}
}
})
}
This is the wrong approach. You know the times, so you know how far off they are in time. You don't need to check over and over again if the time has arrived. Instead work out how many milliseconds until the time in question, then set a timeout for that time.
You basically need to pass different functions to each setTimeout():
function checktime1(){
if(currenttime != lat[i]){
setTimeout(checktime1,30000)
}
else{
console.log("yay the time is right!")
}
}
function checktime2(){
if(currenttime != lat[i]){
setTimeout(checktime2,50000)
}
else{
console.log("yay the time is right!")
}
}
However, this is obviously not scalable. If you have lots of timeouts you will be writing lots of duplicate functions. Worse, if you have a dynamic number of timeouts this won't solve your problem.
Fortunately, javascript lets us declare functions inside another function:
function checktime(timeout){
function loop () {
if(currenttime != lat[i]){
setTimeout(loop,timeout)
}
else{
console.log("yay the time is right!")
}
}
loop();
}
This allows you to dynamically create functions as needed:
checktime(30000);
checktime(50000);
If you need to pass arguments to each timeouts (eg. if you need to display custom alerts) you can just pass it to your outer function and it will be captured in a closure:
function checktime(timeout, message){
function loop () {
if(currenttime != lat[i]){
setTimeout(loop,timeout)
}
else{
console.log(message)
}
}
loop();
}
Then you can do:
checktime(30000, "Yay, the time is right for timer 1");
checktime(50000, "Yay, the time is right for timer 2");
Similarly, if you need to execute custom logic for each timer you can also pass it as an argument (callback):
function checktime(timeout, callback){
function loop () {
if(currenttime != lat[i]){
setTimeout(loop,timeout);
}
else{
console.log("yay the time is right!");
callback(); // <----------------- execute custom logic
}
}
loop();
}
Which you can use like:
checktime(30000, () -> console.log("TIMER 1"));
checktime(50000, () -> alert("TIMER 2"));

Time Calculation returning a NaN result

I am not very good at scripts, but I have created a PDF fillable form to calculate hours worked. When there is no data entered, the result fields show NaN:NaN, is there a way to hide this if the fields are blank?
The script formula I have used is.....
var hrsStart = parseInt(this.getField("hrsstart1").value.split(":")[0]);
var minStart = parseInt(this.getField("hrsstart1").value.split(":")[1]);
var hrsEnd = parseInt(this.getField("hrsend1").value.split(":")[0]);
var minEnd = parseInt(this.getField("hrsend1").value.split(":")[1]);
if (minStart > minEnd) {
var minRez = 60 + minEnd - minStart;
var hrsRez = hrsEnd - 1 - hrsStart;
} else {
var minRez = minEnd - minStart;
var hrsRez = hrsEnd - hrsStart;
}
this.getField("Totalhrs1").value = hrsRez + ":" + minRez;
When there is no data entered, the result fields show NaN:NaN, is there a way to hide this if the fields are blank?
Use NaN checker function isNaN() like below:
if(!(isNaN(hrsRez)) && !(isNaN(minRez)) {
this.getField("Totalhrs1").value = hrsRez + ":" + minRez;
}
Try this:
var startValue = this.getField("hrsstart1").value;
var endValue = this.getField("hrsend1").value;
var timeValue = '';
if(startValue && endValue)
{
var startArr = startValue.split(":");
var endArr = endValue.split(":");
var hrsStart = parseInt(startArr[0]);
var minStart = parseInt(startArr[1]);
var hrsEnd = parseInt(endArr[0]);
var minEnd = parseInt(endArr[1]);
if(!isNaN(hrsStart) && !isNaN(minStart) && !isNaN(hrsEnd) && !isNaN(minEnd))
{
var minRez, hrsRez;
if (minStart > minEnd) {
minRez = 60 + minEnd - minStart;
hrsRez = hrsEnd - 1 - hrsStart;
} else {
minRez = minEnd - minStart;
hrsRez = hrsEnd - hrsStart;
}
timeValue = hrsRez + ":" + minRez;
}
}
this.getField("Totalhrs1").value = timeValue;

Calendar displays 24 hour clock and I need 12 hour clock

I have this e-calendar JavaScript code that is displaying 24hour clock format. How do you get it to change to 12 hour clock? Forgive the chopped up code, I had to delete some of it to create the post.
I have posted the code below:
(function ($) {
var eCalendar = function (options, object) {
// Initializing global variables
var adDay = new Date().getDate();
var adMonth = new Date().getMonth();
var adYear = new Date().getFullYear();
var dDay = adDay;
var dMonth = adMonth;
var dYear = adYear;
var instance = object;
var settings = $.extend({}, $.fn.eCalendar.defaults, options);
function print() {
loadEvents();
var dWeekDayOfMonthStart = new Date(dYear, dMonth, 1).getDay();
var dLastDayOfMonth = new Date(dYear, dMonth + 1, 0).getDate();
var dLastDayOfPreviousMonth = new Date(dYear, dMonth + 1, 0).getDate() - dWeekDayOfMonthStart + 1;
var cBody = $('<div/>').addClass('c-grid');
var cEvents = $('<div/>').addClass('c-event-grid');
var cEventsBody = $('<div/>').addClass('c-event-body');
cEvents.append($('<div/>').addClass('c-event-title c-pad-top').html(settings.eventTitle));
cEvents.append(cEventsBody);
var cNext = $('<div/>').addClass('c-next c-grid-title c-pad-top');
var cMonth = $('<div/>').addClass('c-month c-grid-title c-pad-top');
var cPrevious = $('<div/>').addClass('c-previous c-grid-title c-pad-top');
cPrevious.html(settings.textArrows.previous);
cMonth.html(settings.months[dMonth] + ' ' + dYear);
cNext.html(settings.textArrows.next);
cPrevious.on('mouseover', mouseOver).on('mouseleave', mouseLeave).on('click', previousMonth);
cNext.on('mouseover', mouseOver).on('mouseleave', mouseLeave).on('click', nextMonth);
cBody.append(cPrevious);
cBody.append(cMonth);
cBody.append(cNext);
for (var i = 0; i < settings.weekDays.length; i++) {
var cWeekDay = $('<div/>').addClass('c-week-day c-pad-top');
cWeekDay.html(settings.weekDays[i]);
cBody.append(cWeekDay);
}
var day = 1;
var dayOfNextMonth = 1;
for (var i = 0; i < 42; i++) {
var cDay = $('<div/>');
if (i < dWeekDayOfMonthStart) {
cDay.addClass('c-day-previous-month c-pad-top');
cDay.html(dLastDayOfPreviousMonth++);
} else if (day <= dLastDayOfMonth) {
cDay.addClass('c-day c-pad-top');
if (day == dDay && adMonth == dMonth && adYear == dYear) {
cDay.addClass('c-today');
}
for (var j = 0; j < settings.events.length; j++) {
var d = settings.events[j].datetime;
if (d.getDate() == day && (d.getMonth() - 1) == dMonth && d.getFullYear() == dYear) {
cDay.addClass('c-event').attr('data-event-day', d.getDate());
cDay.on('mouseover', mouseOverEvent).on('mouseleave', mouseLeaveEvent);
}
}
cDay.html(day++);
} else {
cDay.addClass('c-day-next-month c-pad-top');
cDay.html(dayOfNextMonth++);
}
cBody.append(cDay);
}
var eventList = $('<div/>').addClass('c-event-list');
for (var i = 0; i < settings.events.length; i++) {
var d = settings.events[i].datetime;
if ((d.getMonth() - 1) == dMonth && d.getFullYear() == dYear) {
var date = lpad(d.getDate(), 2) + '/' + lpad(d.getMonth(), 2) + ' ' + lpad(d.getHours(), 2) + ':' + lpad(d.getMinutes(), 2);
var item = $('<div/>').addClass('c-event-item');
var title = $('<div/>').addClass('title').html(date + ' ' + settings.events[i].title + '<br />');
var description = $('<div/>').addClass('description').html(settings.events[i].description + '<br />');
item.attr('data-event-day', d.getDate());
item.on('mouseover', mouseOverItem).on('mouseleave', mouseLeaveItem);
item.append(title).append(description);
eventList.append(item);
}
}
$(instance).addClass('calendar');
cEventsBody.append(eventList);
$(instance).html(cBody).append(cEvents);
}
return print();
}
$.fn.eCalendar = function (oInit) {
return this.each(function () {
return eCalendar(oInit, $(this));
});
};
}(jQuery));
getHours returns the range 0-23, so if it's greater than 11, subtract 12.
You could even get fancy and do like
(getHours() + 24) % 12 || 12

Line break TextNode javascript?

I am working on a simple project which is turning out to be difficult for some reason. First let me show you the result I am getting as of now; it's just this:
Leicester City vs Manchester United - 9/21 14:30
Now, I want to have the date and time on a separate line, however, every way I tried has failed me including \n, , document.createElement("br") and some unicode characters. I've really hit a brick wall this time. Any help is welcomed.
p.s.: I am only into my 3rd month of programming
This is my code:
function listEvents(feedRoot) {
var entries = feedRoot.feed.getEntries();
var eventDiv = document.getElementById('events');
if (eventDiv.childNodes.length > 0) {
eventDiv.removeChild(eventDiv.childNodes[0]);
}
var ul = document.createElement('p');
var len = entries.length;
for (var i = 0; i < len; i++) {
var entry = entries[i];
var title = entry.getTitle().getText();
var startDateTime = null;
var startJSDate = null;
var times = entry.getTimes();
if (times.length > 0) {
startDateTime = times[0].getStartTime();
startJSDate = startDateTime.getDate();
}
var entryLinkHref = null;
if (entry.getHtmlLink() != null) {
entryLinkHref = entry.getHtmlLink().getHref();
}
var dateString = (startJSDate.getMonth() + 1) + "/" + startJSDate.getDate();
if (!startDateTime.isDateOnly()) {
dateString += " " + startJSDate.getHours() + ":" +
padNumber(startJSDate.getMinutes());
}
var li = document.createElement('article');
if (entryLinkHref != null) {
entryLink = document.createElement('a');
entryLink.setAttribute('href', entryLinkHref);
entryLink.appendChild(document.createTextNode(title));
li.appendChild(entryLink);
li.appendChild(document.createTextNode(' - ' + dateString));
} else {
li.appendChild(document.createTextNode(title + ' - ' + dateString));
}
ul.appendChild(li);
}
eventDiv.appendChild(ul);
}

Time overlap issue javascript

I am working in add task module in my project.i want to check every time task add check if existing tasks overlap or not. i am almost did but,one problem occur on time overlap condition not allow add task, example if user add tasks below times like below:
09:00 AM - 10:00 AM
10:30 AM - 11:00 AM
if i add tasks to between 10:00 AM to 10:30 AM not allowed in my condition on below:
function disabletime(start_time, end_time) {
var start_date = new Date(new Date(start_time).getTime());
var end_date = new Date(new Date(end_time).getTime());
var disable_times = new Array();
var max_date = 0;
var min_date = 0;
if (tasks_array.length > 0) {
for (var i = 0; i < tasks_array.length; i++) {
var prev_s_date = Date.parse("1-1-2000 " + tasks_array[i].start_time);
var prev_e_date = Date.parse("1-1-2000 " + tasks_array[i].end_time);
var prev_start_date = new Date(new Date(prev_s_date).getTime());
var prev_end_date = new Date(new Date(prev_e_date).getTime());
if (i == 0) {
min_date = prev_start_date.getTime();
max_date = prev_end_date.getTime();
} else {
if (prev_end_date.getTime() > max_date) {
max_date = prev_end_date.getTime();
}
if (prev_start_date.getTime() < min_date) {
min_date = prev_start_date.getTime();
}
}
}
if ((start_date.getTime() == min_date) && (end_date.getTime() == max_date)) {
alert("Check the start and end time for this task!");
return false;
} else if ((start_date.getTime() < min_date) && (end_date.getTime() <= min_date) || (start_date.getTime() >= max_date) && (end_date.getTime() > max_date)) {
} else {
alert("Check the start and end time for this task!");
return false;
}
}
start_date = new Date(start_date.getTime() + 30 * 60000);
while (start_date < end_date) {
disable_times.push([start_date.getHours(), start_date.getMinutes()]);
start_date = new Date(start_date.getTime() + 30 * 60000);
}
return true;
}
here is my code flow, i add all tasks into json array in javascript. every time add new task check existing tasks on json array objects(inside if tasks exist) time overlap or not.
Here is a fiddle
I think it's a 'refactor if you want to debug' case.
Just breaking you problems into well isolated, small, simple problems will lead you to a solution faster than any deep debug cession.
You should break down the complexity of your code by using objects,
so you'll have a clear view on who does what, and you can test
easily each part.
I'm not sure the code below complies with all your needs, but it
should be much easier to use : i defined 2 objects : a task,
and a set of task.
For each i defined pretty simple methods, easy to read and debug.
I did not test the result, but you'll get the idea on how to do what
you want from here.
http://jsfiddle.net/gamealchemist/b68Qa/2/
// ------------------------------
// Task
function Task(startDate, endDate) {
this.start = startDate;
this.end = endDate;
}
// returns wether the time range overlaps with this task
Task.prototype.overlap = function (start, end) {
return (this.start <= end && this.end >= start);
}
// returns a string describing why the task is wrong, or null if ok
function checkTask(start, end) {
if (start > end) return "End time should exceed the start time";
if (start == end) return "End time should not same as the start time";
return null;
}
and now a set of tasks :
// ------------------------------
// Task Set
function TaskSet() {
this.tasks = [];
this.minDate = 0;
this.maxDate = 0;
}
// returns a string describing why the task cannot be added, or null if ok
TaskSet.prototype.check = function (start, end) {
var tasks = this.tasks;
// 1. Check date is valid
var dateCheck = checkTask(start, end);
if (dateCheck) return dateCheck;
// 2. overlap check
for (var i = 0; i < tasks.length; i++) {
var thisTask = tasks[i];
if (thisTask.overlap(start, end)) {
return 'time overlaps with another task';
}
}
return null;
}
// add the task.
TaskSet.prototype.add = function (start, end) {
var tasks = this.tasks;
if (task.length) {
this.minDate = start;
this.maxDate = end;
}
if (start < minDate) minDate = start;
if (end > maxDate) maxDate = end;
// you might want to check before inserting.
tasks.push(new Task(start, end));
}
// displays the current task inside the tasks div.
TaskSet.prototype.show = function () {
var tasks_array = this.tasks;
$("#tasks").html('');
$.each(tasks_array, function (index, item) {
var newRowContent = "<div>" + item.start_time + "-" + item.end_time + "</div>";
$("#tasks").append(newRowContent);
});
}
Let's use those objects :
// ---------------------------
var myTasks = new TaskSet();
$("#addtask").click(handle_AddTask_Clicked);
function handle_AddTask_Clicked(e) {
e.preventDefault();
var start = $("#task_stime").val();
var end = $("#task_etime").val();
var start_time = Date.parse("1-1-2000 " + start);
var end_time = Date.parse("1-1-2000 " + end);
var checkCanAdd = myTasks.check(start_time, end_time);
if (!checkCanAdd) {
myTasks.add(start_time, end_time);
myTasks.show(); // notice you might auto-refresh withinin add
} else {
alert(checkCanAdd);
}
}
finally i got solution from my friends on below code:
function disabletime(start_time, end_time) {
var start_date = start_time;
var end_date = end_time;
var disable_times = new Array();
var max_date = 0;
var min_date = 0;
var startTimeOverlapIndex = -1;
var endTimeOverlapIndex = -1;
var sameDateIndex = -1;
if (tasks_array.length > 0) {
for (var i = 0; i < tasks_array.length; i++) {
var prev_s_date = new Date("January 1, 1111 " + tasks_array[i].start_time);
var prev_e_date = new Date("January 1, 1111 " + tasks_array[i].end_time);
if(end_date<=prev_e_date) {
if(end_date>prev_s_date) {
endTimeOverlapIndex = i+1;
break;
}
}
if(start_date<prev_e_date) {
if(start_date>=prev_s_date) {
startTimeOverlapIndex = i+1;
break;
} else {
if(end_date>prev_s_date) {
endTimeOverlapIndex = i+1;
break;
}
}
}
if(start_date.toString()===prev_s_date.toString() && end_date.toString()===prev_e_date.toString()) {
sameDateIndex = i+1;
break;
}
}
if(sameDateIndex>0) {
alert("Sorry! your time cannot be same as task ("+startTimeOverlapIndex+"), please check again!");
return false;
} else if(startTimeOverlapIndex>0) {
alert("Sorry! your START time is overlaping with task ("+startTimeOverlapIndex+"), please check again!");
return false;
} else if(endTimeOverlapIndex>0) {
alert("Sorry! your END time is overlaping with task ("+endTimeOverlapIndex+"), please check again!");
return false;
} else {
//do whatever you do
return true;
}
}
return true;
}
Live link on fiddle find here
http://jsfiddle.net/mur7H/
It is 100% working. Please find below the correct answer with date and time overlapping.
function isBetween(ST, ET, PST, PET) {
var res = false;
if (((ST - PST) * (ST - PET) <= 0) || ((ET - PST) * (ET - PET) <= 0) || ((PST - ST) * (PST - ET) <= 0) || ((PET - ST) * (PET - ET) <= 0)) res = true;
return res;
}
function disabletime(start_time, end_time) {
debugger;
var start_date = new Date(start_time);
var end_date = new Date(end_time);
var disable_times = new Array();
var max_date = 0;
var min_date = 0;
var startTimeOverlapIndex = -1;
var endTimeOverlapIndex = -1;
var sameDateIndex = -1;
var resultA = true;
if (KitchenHourList.length > 0) {
for (var i = 0; i < KitchenHourList.length; i++) {
var prev_s_date = new Date(KitchenHourList[i].KitchenFromDate + " " + KitchenHourList[i].KitchenFromTime);
var prev_e_date = new Date(KitchenHourList[i].KitchenToDate + " " + KitchenHourList[i].KitchenToTime);
var STMinut = (start_date.getHours() * 60) + start_date.getMinutes();
var ETMinut = (end_date.getHours() * 60) + end_date.getMinutes();
var PSTMinut = (prev_s_date.getHours() * 60) + prev_s_date.getMinutes();
var PETMinut = (prev_e_date.getHours() * 60) + prev_e_date.getMinutes();
if (end_date <= prev_e_date) {
if (end_date > prev_s_date) {
if (isBetween(STMinut, ETMinut, PSTMinut, PETMinut)) {
endTimeOverlapIndex = i + 1;
break;
}
}
}
if (start_date < prev_e_date) {
if (start_date >= prev_s_date) {
if (isBetween(STMinut, ETMinut, PSTMinut, PETMinut)) {
startTimeOverlapIndex = i + 1;
break;
}
} else {
if (end_date > prev_s_date) {
if (isBetween(STMinut, ETMinut, PSTMinut, PETMinut)) {
{
endTimeOverlapIndex = i + 1;
break;
}
}
}
}
}
if (start_date.toString() === prev_s_date.toString() && end_date.toString() === prev_e_date.toString()) {
sameDateIndex = i + 1;
break;
}
}
if (sameDateIndex > 0) {
alert("Sorry! your time cannot be same as row (" + startTimeOverlapIndex + "), please check again!");
return false;
} else if (startTimeOverlapIndex > 0) {
alert("Sorry! your START time is overlaping with row (" + startTimeOverlapIndex + "), please check again!");
return false;
} else if (endTimeOverlapIndex > 0) {
alert("Sorry! your END time is overlaping with row (" + endTimeOverlapIndex + "), please check again!");
return false;
} else {
return true;
}
}
return true;
}

Categories

Resources