Find is date between array of start and end dates - javascript

I have a array of objects containing dates, if a user added another start and end date it cannot overlap with any existing dates in the array.
Using Moment I have this loop but no alert is fired when I input a date that overlaps
Using the input dates, startDate: "2013-09-02T00:00:00", endDate: "2015-05-05T00:00:0, the loop over the last array item should fire the alert, as the dates overlap.
let resultData = data.row;
let array = this.props.sectionData;
let inputStartDate = Moment(resultData.startDate, "DD/MM/YYYY");
let inputEndDate = Moment(resultData.endDate, "DD/MM/YYYY");
array.forEach( function (i) {
if(i.startDate && i.endDate) {
let startDate = Moment(i.startDate, "DD/MM/YYYY");
let endDate = Moment(i.endDate, "DD/MM/YYYY");
if (inputStartDate.isBetween(startDate, endDate) || inputEndDate.isBetween(startDate, endDate)) {
alert('date range cannot overlap');
}
}
});
My data:
[
{"id": 3,
"startDate": 2013-09-01T00:00:00,
"endDate": 2013-09-01T00:00:00,
"description": null,
"userId": 900,
"userName": "",
"documents": [],
},
{
"id": 5,
"startDate": 2013-09-01T00:00:00,
"endDate": 2013-09-01T00:00:00,
"description": null,
"userId": 1,
"userName": "",
"documents": [],
"contributors": []
},
{
"id": 6,
"startDate": "2013-09-01T00:00:00",
"endDate": "2014-08-31T00:00:00",
"description": "content",
"userId": 1,
"userName": ""
},

Let moment parse the object. See https://plnkr.co/edit/OqKNDsSWvcMc3PXOcu9F?p=preview for a working example.
Explanation:
let inputStartDate = moment("2013-09-02T00:00:00");
let inputEndDate = moment("2015-05-05T00:00:00");
As ADyson explained your were passing in the incorrect formats. Also you are missing quotes in your test data around your dates for ids 3 and 5.

Related

how can i get the "validade" value from the array and get only?

The array
{"status":true,"data":[{"id":1,"pessoa_id":75505,"created_at":"2022-02-
01T17:42:46.000000Z","holder":"LEONARDO LIMA","validade":"2026-06-
01","bandeira":"Mastercard"}]}
Inside digiAno I wanted to put only the year value of the array
this.dadosCC.reset({
'parcelas': '1',
'digiNumero': ['**** **** ****', cartao.mask] ,
'digiNome': cartao.holder,
'digiMes': '',
'digiAno': cartao.validade,
'valor': this.cartS.cart.valorTotal,
'cpfInput': this.userS.user.cpf,
'cardToken': this.cardToken,
'digiCVV':''
});
If you want to get the entire information of validade and put that information inside cartao use this code:
myObject: any = {
"status": true,
"data": [{
"id": 1,
"pessoa_id": 75505,
"created_at": "2022-02-01T17:42:46.000000Z",
"holder": "LEONARDO LIMA",
"validade": "2026-06-01",
"bandeira": "Mastercard"
}]
};
cartao: any = this.myObject.data[0].validade;
If you want to get year, month and the day use this.
myObject: any = {
"status": true,
"data": [{
"id": 1,
"pessoa_id": 75505,
"created_at": "2022-02-01T17:42:46.000000Z",
"holder": "LEONARDO LIMA",
"validade": "2026-06-01",
"bandeira": "Mastercard"
}]
};
cartao: any = this.myObject.data[0].validade;
dateArray: any = this.cartao.split('-');
year = this.dateArray[0];
month = this.dateArray[1];
day = this.dateArray[2];

Set and compare dates to check credit card validity

I have customers signing up for a 12 monthly installment option. I need to know if their credit card will be valid for at least the duration of the installment option exactly 12 months.
Using the card.exp_year and card.exp_month from the object received below, how would I work out if this credit card will be valid exactly 1 year from now. I assume I have to use the Date() function.
{
"id": "tok_xxxxxxxx",
"object": "token",
"card": {
"id": "card_xxxxxxxx",
"object": "card",
"address_city": null,
"address_country": "BE",
"address_line1": null,
"address_line1_check": null,
"address_line2": null,
"address_state": null,
"address_zip": null,
"address_zip_check": null,
"brand": "Visa",
"country": "CA",
"cvc_check": "unchecked",
"dynamic_last4": null,
"exp_month": 7,
"exp_year": 2019,
"funding": "credit",
"last4": "3086",
"metadata": {},
"name": "John Doe ",
"tokenization_method": null
},
"client_ip": "149.xxx.xxx.xxx",
"created": 1530xxxxxx,
"livemode": true,
"type": "card",
"used": false
}
Thanks, Luca! Final working solution!
var cardYear = new Date();
cardYear.setMonth(12-1); // jan = 0 so minus 1
cardYear.setYear(2019);
console.log(cardYear);
var nextYearFromNow = new Date(new Date().setFullYear(new Date().getFullYear() + 1));
console.log(nextYearFromNow);
console.log(compareTime(cardYear, nextYearFromNow));
function compareTime(time1, time2) {
return new Date(time1) > new Date(time2); // true if time1 is later
}
or
var year = user.attributes.token.card.exp_year;
var month = user.attributes.token.card.exp_month;
var cardYear = new Date(year, month, 0); // returns date according to card and sets day to last day of month becuase credit cards are set to expire on the last day of a month
var nextYearFromNow = new Date(new Date().setFullYear(new Date().getFullYear() + 1));
var expiry = compareTime(cardYear, nextYearFromNow); // if false card is too short
function compareTime(time1, time2) {
return new Date(time1) > new Date(time2); // true if time1 is later
}

How do I create a new object from an existing object in Javascript?

Working on JavaScript app and need help in creating a new object from response received from ajax call.
The output received is array of objects, sample format below:
{
"items": [
{
"id": "02egnc0eo7qk53e9nh7igq6d48",
"summary": "Learn to swim",
"start": {
"dateTime": "2017-03-04T19:00:00+05:30"
}
}
]
}
However, my component expects JS Object in the following format:
{
id: "e1",
title: "Express",
start: "Jan 13, 2010",
description: "Jan 13, 2010"
}
Is following approach correct, please suggest better approach if any
var content = {
"items": [{
"id": "02egnc0eo7qk53e9nh7igq6d48",
"summary": "Learn to code",
"start": {
"dateTime": "2017-03-04T19:00:00+05:30"
}
}
}
};
var gcalEvents = {};
var jsonObj = {
"id": "e1",
"title": "Oracle Application Express",
"start": "Jan 13, 2010",
"description": "Jan 13, 2010"
};
console.log(content.items.length);
for (var index = 0; index < content.items.length; index++) {
var obj = content.items;
console.log(obj);
jsonObj.id = obj[index]["id"];
jsonObj.title = obj[index].summary;
jsonObj.start = obj[index].start.dateTime;
jsonObj.description = "";
console.log(jsonObj);
gcalEvents[index] = jsonObj;
}
console.log(gcalEvents);
You could take a more functional approach with the following:
var parsed = content.items.map(function (item) {
return {
id: item.id,
title: item.summary,
start: item.start.dateTime,
description: item.start.dateTime
}
})
This uses the map method that is attributed with arrays to loop over each item of the array and return a new array of parsed objects.
Take a look at this fuller example.
I have another way to convert this content.
Using Underscore.js to make the code more readable.
Here is the example:
var content = {
"items": [{
"id": "02egnc0eo7qk53e9nh7igq6d48",
"summary": "Learn to code",
"start": {
"dateTime": "2017-03-04T19:00:00+05:30"
}
}, {
"id": "nj4h567r617n4vd4kq98qfjrek",
"summary": "Modern Data Architectures for Business Insights at Scale Confirmation",
"start": {
"dateTime": "2017-03-07T11:30:00+05:30"
}
}]
};
var result = _.map(content.items, function(item) {
return {
id: item.id,
title: item.summary,
start: item.start.dateTime,
description: ""
};
});
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
The result as following:
[
{
"id": "02egnc0eo7qk53e9nh7igq6d48",
"title": "Learn to code",
"start": "2017-03-04T19:00:00+05:30",
"description": ""
},
{
"id": "nj4h567r617n4vd4kq98qfjrek",
"title": "Modern Data Architectures for Business Insights at Scale Confirmation",
"start": "2017-03-07T11:30:00+05:30",
"description": ""
}
]
At the core, you are trying to 'map' from one set of data to another. Javascript's mapping function of array should be sufficient. Eg.
var content = {
"items": [{
"id": "02egnc0eo7qk53e9nh7igq6d48",
"summary": "Learn to code",
"start": {
"dateTime": "2017-03-04T19:00:00+05:30"
}
}]
};
var results = content.items.map(function (item) {
return {
id: item.id,
title: item.summary,
start: item.start.dateTime,
description: ""
};
});
console.log(results);
var jsonObj=[];
for (var index = 0; index < content.items.length; index++) {
var obj = {};
console.log(obj);
obj["id"]=content.items[index].id;
obj["title"]=content.items[index].summary;
obj["start"]=content.items[index].start.dateTime;
obj["description"]="";
jsonObj.push(obj);
console.log(jsonObj);
//gcalEvents[index] = jsonObj;
}
This will give you jsonObj as your desired json object.
Hope this helps :)
Here's the fixed code:
One error was when you've listed the content items, a "]" was missing at the end.
The second one was that you were trying to assign a values to an undefined object, you first need to define the object eg: jsonObj = {}; and then do the assigning of values.
I've preferred to do the object define and assigning of the values in one go.
In order to have the output as an array, you just have to define the colection as an array and not am object eg: var gcalEvents = []
var content = {
"items": [
{
"id": "02egnc0eo7qk53e9nh7igq6d48",
"summary": "Learn to code",
"start": {
"dateTime": "2017-03-04T19:00:00+05:30"
}
},
{
"id": "nj4h567r617n4vd4kq98qfjrek",
"summary": "Modern Data Architectures for Business Insights at Scale Confirmation",
"start": {
"dateTime": "2017-03-07T11:30:00+05:30"
}
}
]
};
var gcalEvents = [];
var jsonObj = {
"id": "e1",
"title": "Oracle Application Express",
"start": "Jan 13, 2010",
"description": "Jan 13, 2010"
};
//console.log(content.items.length);
for(var index=0; index < content.items.length; index++){
var obj = content.items[index];
//console.log(obj);
jsonObj = {
'id': obj["id"],
'title': obj.summary,
'start': obj.start.dateTime,
'description': ""
}
//console.log(jsonObj);
gcalEvents[index] = jsonObj;
}
console.log(gcalEvents);

Nested loops for mongodb arrays in Node.js

Hey so I'm reasonably new to Node.js and Mongodb, I am making a roster creation system and I want to make it so that only two users/employees can work on a given shift. For simplicity the shifts are split into 'day' and 'night' which are in a table of radio buttons that the user can chosen. Onload of the shifts page however I want to disable those buttons which have already been chosen by two other users.
I think that the outer loop should iterate through the shifts array of the users (Monday --> Sunday), the inner loop should then iterate through each user in the mongodb database. Eventually I want to have the code working for each day of the week but for now just need Monday to function properly.
Thanks for any help and advise
function disableOnLoad() {
console.log("disableOnLoad reached");
var dayCount=0;
var nightCount=0;
$.getJSON( '/shiftsTable', function( data ) {
$.each(data, function(){
userListData = data;
for(i = 0; i < 7; i++) {
**//$.each(data, function(){**
if(this.shifts[i]=='day'){
if(i==0){
dayCount++;
console.log("dayCount: "+dayCount);
if(dayCount>2){document.getElementById("monDay").disabled=true;}
}
}
else if(this.shifts[0]=='night'){
nightCount++;
if (nightCount>2){document.getElementById("monNight").disabled=true;}
}
}
});
});
};
Assuming this is the data
data = [{
"_id": "589f60999c471a32c6a3a380",
"name": "Ciara",
"position": "Sales assistant",
"location": "Dublin",
"admin": 0,
"shifts": ["day", "day", "night", null, null, null, null, "23"]
},
{
"_id": "589f60999c471a32c6a3a380",
"name": "Ciara2",
"position": "Sales assistant",
"location": "Dublin",
"admin": 0,
"shifts": ["day", "day", "night", null, null, null, null, "23"]
},{
"_id": "589f60999c471a32c6a3a380",
"name": "Ciara3",
"position": "Sales assistant",
"location": "Dublin",
"admin": 0,
"shifts": ["day", "day", "night", null, null, null, null, "23"]
}];
So this code works for me
$.each(data, function(val) {
userListData = data;
for (i = 0; i < 7; i++) { //* * //$.each(data, function(){**
if (i==0 && this.shifts[i] == 'day') {
dayCount++;
if (dayCount == 2) {
document.getElementById("monDay").disabled = true;
}
} else if (i==0 && this.shifts[i] == 'night') {
nightCount++;
if (nightCount == 2) {
document.getElementById("monNight").disabled = true;
}
}
}
});
}
Let me know if it works.

Create JSON with data from database and JavaScript generated

I need to create a calendar view with fullcalendar.io. For some dates, I have a specific price in my database and I retrieve it, but for some dates (without specific prices) I need to put the usual rates in the objects I need to create with JavaScript. Problem is now because I don't know how to make JSON for that.
In short: I need to have a price for every date, but for some dates I get data from database. How do I create such JSON objects in JavaScript?
I have this code:
var db_data = [
{
"id": 5,
"user_id": 1,
"article_id": 5,
"title": "",
"start": "2016-03-25 15:18:46"
},
{
"id": 4,
"user_id": 1,
"article_id": 5,
"price": 55,
"title": "",
"start": "2016-03-15 15:18:46"
},
{
"id": 3,
"user_id": 1,
"article_id": 5,
"price": 35,
"title": "",
"start": "2016-03-07 15:18:46"
},
{
"id": 2,
"user_id": 1,
"article_id": 5,
"price": 22,
"title": "drugi",
"start": "2016-03-05 15:18:46"
},
{
"id": 1,
"user_id": 1,
"article_id": 5,
"price": 44,
"title": "prvi",
"start": "2016-02-04 15:18:46"
}
];
// declare variables
var period_start = new Date('2016-02-02'),
period_end = new Date('2016-03-03'),
current_date = period_start,
array_of_all_dates = [];
// Create a populated array of dates
// Create a populated array of dates
while (current_date.getTime() <= period_end.getTime()) {
array_of_all_dates.push(current_date);
current_date = new Date(+current_date);
current_date.setDate(current_date.getDate() + 1);
}
// Now loop over the array of populated dates and mutate, so something like
array_of_all_dates = array_of_all_dates.map(function (date) {
var found_in_db = db_data.filter(function (db_data) {
return new Date(db_data.start.replace(" ", "T")).getTime() === date.getTime(); // You need to do this comparison better!
});
if (found_in_db.length > 0) {
return found_in_db[0];
}
var new_object = {
title: '',
start: date,
price: '{{$article->price}}'
};
console.log(new_object);
return new_object;
});
console.log('result'+array_of_all_dates);
drawCalendar(array_of_all_dates);
And with this code I get data from database and dates (start) which are not excist in database I create with JavaScript.
But with this function I get this data and I can't create calendar:
I also try with this:
// Now loop over the array of populated dates and mutate, so something like
array_of_all_dates = array_of_all_dates.map(function (date) {
var found_in_db = db_data.filter(function (db_data) {
var db_data_date = new Date(db_data.start.replace(" ", "T"));
return db_data_date.getFullYear() === date.getFullYear() &&
db_data_date.getMonth() === date.getMonth() &&
db_data_date.getDay() === date.getDay();
});
if (found_in_db.length > 0) {
return found_in_db[0];
}
var new_object = {
a_property: 'some_default_value',
start: date
};
console.log(new_object);
return new_object;
});
But currently I get this:
I don't see how this:
new Date(db_data.start.replace(" ", "T")).getTime() === date.getTime()
can ever be true. The dates in db_data have a time set in them "2016-03-15 15:18:46", but the dates you create in array_of_all_dates do not Date('2016-02-02').
Your second date comparison seems to work, but I am unclear what it is you hope to be the result of the:
array_of_all_dates.map( ... );
In some case you return an element from db_data which looks like this:
{ "id": 5", "user_id": 1, "article_id": 5, "title": "", "start": "2016-03-25 15:18:46" }
and if there was no "match" you return an object that looks like this:
{ a_property: 'some_default_value', start: date }
Note that all the original elements of array_of_all_dates are replaced by this operation.
What is it that you want to end up in array_of_all_dates so you can pass it to drawCalendar?

Categories

Resources