Set and compare dates to check credit card validity - javascript

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
}

Related

Read JSON with Current Date and get key value using Javascript?

I am trying to get the count from JSON response which has current date in the key.
Json Response:
[
{
"type": {
"id": "mobile",
"name": "mobile",
"description": "",
"total_count": 0
},
"counts": [
{
"date": "2018-09-06",
"timestamp": 1536192000000,
"count": 20
},
{
"date": "2018-09-07",
"timestamp": 1536278400000,
"count": 10
}
]
},
{
"type": {
"id": "lap",
"name": "lap",
"description": "",
"total_count": 0
},
"counts": [
{
"date": "2018-09-06",
"timestamp": 1536192000000,
"count": 19
},
{
"date": "2018-09-07",
"timestamp": 1536278400000,
"count": 20
}
]
}
]
My New try as per vikscool code:
var json_count = JSON.parse(getcounts);
var curDate = getCurrentDate();
var mobilcount = () => json_count.map(ct => {
const count = ct.counts;
const getDate = count.find(dt => dt.date === curDate);
window.alert('count is ', getDate.count);
return {getDate};
});
mobilcount();
function getCurrentDate () {
var nowDate = new Date();
var month = (nowDate.getMonth() + 1).toString().length == 1
? '0' + (nowDate.getMonth() + 1)
: (nowDate.getMonth() + 1);
var day = nowDate.getDate().toString().length == 1
? '0' + nowDate.getDate()
: +nowDate.getDate();
return nowDate.getFullYear() + '-' + month + '-' + day;
}
output: "count is "
but there is no count printed from json.
Is there any solution in Javascript I can get the current date and get the counts.
I need to get the count as 10 in mobilcount.
As the dates are stored in the JSON Array key named as the counts of the first object of the json_count you can not fetch it using:
var instance_count=json_count[0].values[2].count;
As your json object does not have any key named as values.
What you have to do is first access the counts key then get the particular object from it which contains the particular(current date as in your case) and then get the counts from it.
Below is a sample code to get the particular date's count:
//assuming this is the Json response you are getting as complete JSON response is not provided by the OP.
var getcounts = `[{"type":{"id":"mobile","name":"mobile","description":"","total_count":0},"counts":[{"date":"2018-09-05","timestamp":1533686400000,"count":0},{"date":"2018-09-06","timestamp":1533772800000,"count":8}]}]`;
//parsing the given json String
var json_count = JSON.parse(getcounts);
function getCountForCurrentDate() {
var curDate = getCurrentDate(); //for which the data is to be fetched and making in format of the dates in JSON as yyyy-mm-dd
//finding the particular object that contains the current date
var searchedObj = json_count[0]['counts'].find(f => f['date'] == curDate);
if(searchedObj!==undefined)
console.log('count is', searchedObj['count']);
}
function getCurrentDate() {
var nowDate = new Date();
var month = (nowDate.getMonth() + 1).toString().length == 1 ? '0' + (nowDate.getMonth() + 1) : (nowDate.getMonth() + 1);
var day = nowDate.getDate().toString().length == 1 ? '0' + nowDate.getDate() : +nowDate.getDate();
return nowDate.getFullYear() + '-' + month + '-' + day;
}
getCountForCurrentDate();
Here in the snippet above, i have created two functions getCurrentDate() to get the current date in the format it is stored in JSON response and getCountForCurrentDate() to get the count from the json_count variable.
Update 1 as per the new requirement is given by OP
The given JSON object is as follows:
var json_count = [
{
type: {
id: "mobile",
name: "mobile",
description: "",
total_count: 0
},
counts: [
{
date: "2018-09-06",
timestamp: 1536192000000,
count: 20
},
{
date: "2018-09-07",
timestamp: 1536278400000,
count: 10
}
]
},
{
type: {
id: "lap",
name: "lap",
description: "",
total_count: 0
},
counts: [
{
date: "2018-09-06",
timestamp: 1536192000000,
count: 19
},
{
date: "2018-09-07",
timestamp: 1536278400000,
count: 20
}
]
}
];
And now as the object has two entities one for mobile and another for lap we can fetch the particular values as:
var mobile = json_count.find(f=>f['type']['id']=='mobile');//comparing the value present in the json object at location type.id to 'mobile' (change it to 'lap' or anything that is present in the id of the object).
and now to get the count for it we do as:
var mobile_count = mobile.counts.find(f=>f['date']=='2018-09-07');//replace the static date with the date you want to fetch the count from
and then access the count as:
console.log(mobile_count.count);
//output:10

How to find upcoming event in array based on current time

I have an array of events and i'd like to iterate through that array and find the next upcoming event based on its start time compared to the current start time.
Basically, say its currently 3:30pm and there are events starting at 12:00pm, 2pm, 4pm, 5pm.. I'd like to get the event that starts at 4pm.
SAMPLE DATA:
{
"cache_time": 1470678992,
"events": [
{
"title": "EVENT TITLE",
"start_time": "12:00AM",
"end_time": "12:00AM"
},
{
"title": "EVENT TITLE",
"start_time": "8:00AM",
"end_time": "10:00AM"
},
{
"title": "EVENT TITLE",
"start_time": "10:00AM",
"end_time": "12:00PM"
},
{
"title": "EVENT TITLE",
"start_time": "1:00PM",
"end_time": "2:30PM"
},
{
"title": "EVENT TITLE",
"start_time": "2:30PM",
"end_time": "3:00PM"
},
{
"title": "EVENT TITLE",
"start_time": "3:00PM",
"end_time": "4:00PM"
}
]
}
EDIT:
what i've done so far to get the CURRENT meeting but i'm having trouble getting the next meeting when the current meeting is UNKNOWN.
var _this = this;
var date = new Date();
var currentHour = date.getHours();
var currentMins = date.getMinutes();
var reqStartTime = new Date();
reqStartTime.setHours(currentHour, currentMins, 0);
var reqEndTime = new Date(reqStartTime.getTime() + 2 * 60000);
for (var e in EVENT_DATA.events) {
var start_time = EVENT_DATA.events[e].start_24time;
var end_time = EVENT_DATA.events[e].end_24time;
var startTime = new Date();
var endTime = new Date();
startTime.setHours(start_time.substring(0,2), start_time.substring(3,5), 0);
endTime.setHours(end_time.substring(0,2), end_time.substring(3,5), 0);
if ( (reqEndTime > startTime && reqEndTime < endTime) || (reqStartTime > startTime && reqStartTime < endTime) ) {
return EVENT_DATA.events[e];
}
}
Because your start_time is a non-standard format, one thing we will need to do is convert it into a usable value. We will combine it with the start_date to get our comparison value.
Since we can't assume the events are in order, we'll also be taking that into account.
(function(data) {
var currentTime = new Date();
var getStartTime = function(event) { // This function converts the time into a usable format and returns it as a Date object
try {
return new Date(event.start_date + ' ' + event.start_time.replace(/(AM|PM)/, ' $1'));
} catch(ex) { return null; }
};
var sortedEvents = jQuery(data.events).sort(function(a, b) {
return getStartTime(a) > getStartTime(b) ? 1 : -1;
}).toArray(); // Get an array of sorted events
for (var i = 0; i < sortedEvents.length; i++) {
if (getStartTime(sortedEvents[i]) < currentTime) { continue; }
return sortedEvents[i]; // Starts now or after
}
return null; // No matches
})(sample_data);
Original sample data from question:
"events": [
{
"title": "EVENT TITLE",
"start_time": "12:00AM",
"end_time": "12:00AM",
"start_24time": "00:00",
"end_24time": "00:00",
"start_date": "July 29, 2016",
"end_date": "September 03, 2016",
"display_date": "July 29 - September 03, 2016"
}, ...
]

Find is date between array of start and end dates

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.

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?

Group JSON Data in Jquery usinng Underscore.js

I would like to format my JSON data to display Chart in my reporting templates.I want to produce a daily reporting chart with date wise Approved, Rejected and Pending data. My current JSON is:
json_data = '[
{"Approved":1,"updated_date":"2015-03-07"},
{"Approved":1,"updated_date":"2015-03-07"},
{"Rejected":1,"updated_date":"2015-03-07"},
{"Pending":1,"updated_date":"2015-03-07"},{"Approved":1,"updated_date":"2015-03-07"}
]';
I want to achieve this output
$data= '[
{
"date": "1 Mar",
"approved": 0,
"completed": 0,
"rejected": 0
},
{
"date": "2 Mar",
"approved": 0,
"completed": 0,
"rejected": 0
},
{
"date": "3 Mar",
"approved": 9,
"completed": 20,
"rejected": 11
},
{
"date": "4 Mar",
"approved": 20,
"completed": 50,
"rejected": 30
},
{
"date": "5 Mar",
"approved": 40,
"completed": 50,
"rejected": 10
},
{
"date": "6 Mar",
"approved": 35,
"completed": 70,
"rejected": 20
},
{
"date": "7 Mar",
"approved": 50,
"completed": 80,
"rejected": 30
}];'
I want to display only last 7 days data report through CHART.
You should first filter initial data by 'updated_date' (when the date is including in last 7 days), then group by 'updated_date' and then aggregate all desired properties by groups. Using underscore this will look something like this:
var json_data = '[{"Approved":1,"updated_date":"2015-03-07"}, {"Approved":1,"updated_date":"2015-03-07"}, {"Rejected":1,"updated_date":"2015-03-07"}, {"Pending":1,"updated_date":"2015-03-07"}, {"Approved":1,"updated_date":"2015-03-07"}, {"Approved":1, "Rejected": 1, "updated_date":"2015-03-08"}, {"Pending":17,"updated_date":"2015-03-02"} ]';
var json = JSON.parse(json_data);
var today = new Date('2015-03-10'); // new Date();
var sevenDays = 7 * 24 * 60 * 60 * 1000;
var result = _.map(_.groupBy(_.filter(json, function (item) {
var dateDiff = today.getTime() - new Date(item.updated_date).getTime();
return (dateDiff >= 0 && dateDiff < sevenDays);
}), 'updated_date'), function (g, key) {
var res = _.reduce(g, function (memo, item) {
return {
approved: memo.approved + (item.Approved | 0),
completed: memo.completed + (item.Completed | 0),
rejected: memo.rejected + (item.Rejected | 0),
pending: memo.pending + (item.Pending | 0),
};
}, { approved: 0, completed: 0, rejected: 0, pending: 0 });
res.date = key;
return res;
});
Here is a Live demo in JsFiddle
For the sake of readability please use the good old for loops.
P.S. beware of JavaScript dates and time zones if you're doing this on client side.
function sum(numbers) {
return _.reduce(numbers, function(result, current) {
if(_.isUndefined(current))
return result;
return result + parseFloat(current);
}, 0);
}
var result = _.chain(json_data)
.groupBy("updated_date")
.map(function(value, key) {
return {
updated_date: key,
Approved: sum(_.pluck(value, "Approved")),
Rejected: sum(_.pluck(value, "Rejected")),
Pending: sum(_.pluck(value, "Pending"))
}
})
.last(7)
.value();
console.log(JSON.stringify(result));

Categories

Resources