Apply function to object filled with numbers - javascript

I have this simple function that adds a certain number of days to a given date and gets the new date:
var adddays = 401;
var theDate = new Date(2014, 01, 01);
var myNewDate = new Date(theDate);
myNewDate.setDate(myNewDate.getDate() + adddays);
console.log(myNewDate);
Rather than doing one date at a time, I'm now getting dates in an object like this: {543,563,601,629,650,672,698,718}
The question is how I can run all these days through this function to get an object with newly formatted dates. These numbers in the object would substitute for adddays. I know I need a for loop, but I'm a little new to JS to figure it out.

var theDate = new Date(2014, 01, 01);
var newDates = ([543,563,601,629,650,672,698,718]).map(function (e) {
var adddays = e;
var myNewDate = new Date(theDate);
myNewDate.setDate(myNewDate.getDate() + adddays);
console.log(myNewDate);
return myNewDate;
})
or
var str = "{543,563,601,629,650,672,698,718}";
var theDate = new Date(2014, 01, 01);
var newDates = (str.substr(1,str.length-1).split(',')).map(function (e) {
var adddays = parseInt(e,10);
var myNewDate = new Date(theDate);
myNewDate.setDate(myNewDate.getDate() + adddays);
console.log(myNewDate);
return myNewDate;
})

The string you are receiving is not a valid javascript Object and looks more like an array. We will first have to transform it from a string to an array.
var daysToAdd = "{543,563,601,629,650,672,698,718}";
//Removing the {} brackets to turn it into a CSV
daysToAdd = daysToAdd.substring(1,daysToAdd.length-1)
//Using split to turn our values into an array
daysToAdd = daysToAdd.split(',');
//daysToAdd now looks like ["543","563","601","629","650","672","698","718"]
We will want to make a function that accepts the base data and returns the adjusted dates for re-usability. In our function we can use Array.map to call a function on each element in our array
function addAllDaysToDate(daysToAdd,referenceDate){
var adjustedDays = daysToAdd.map(function(addDays){
var date = new Date();
//+variable is shorthand for parseInt(variable);
date.setDate(referenceDate.getDate() + (+addDays));
return date;
});
//Our adjustedDays is now an array of Date objects
return adjustedDays;
}
We can then use our function to get the adjusted dates
var theDate = new Date(2014, 01, 01);
var myNewDates = addAllDaysToDate(daysToAdd,theDate)

Related

Turning an Integer Value into a Date Using that Integer and the Current Month

I have a function in my MongoDB/Node backend where I calculate a nextPaymentDate based on a combination of the current date and value(s) in a field (which is an array) titled paymentDateInts.
I have some logic that determines what is the correct integer of these two to assign to nextPaymentDateInt. This looks like this:
let currentDate = new Date();
let currentDateInt = currentDate.getDate();
let paymentDateInts = [1, 15];
let firstDateInt = paymentDateInts[0];
let secondDateInt = paymentDateInts[1];
let nextPaymentDateInt;
if (firstDateInt < currentDateInt) {
nextPaymentDateInt = firstDateInt;
} else {
nextPaymentDateInt = secondDateInt;
}
However, I want nextPaymentDate to be a date, not an integer. So how do I take the integer returned from the above function, and then turn that into a date.
UPDATE:
It just occurred to me that this is a little more complicated than I first assumed. Because I need to generate a date using that integer and either the current month, or the following month - whichever should apply.
In other words, if the second value is 15, and today is the 10th, then I should get a date with the current month and the integer 15. However, if today's date is beyond that 15th, then the date calculated should be for the next month and the integer 1.
You can use the new Date(year, monthIndex, day); constructor to construct your Date object
let nextPaymentDate = new Date(d.getFullYear(), d.getMonth(), nextPaymentDateInt);
Note:
There's no need to declare useless variables such as paymentDateInts, firstDateInt and secondDateInt, just compare the currentDateInt with 15 and construct your Date accordingly:
let currentDate = new Date();
let currentDateInt = currentDate.getDate();
let nextPaymentDate;
if (15 >= currentDateInt) {
nextPaymentDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDateInt);
} else {
nextPaymentDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 1);
}
Demo:
let currentDate = new Date();
let currentDateInt = currentDate.getDate();
var nextPaymentDate;
if (15 >= currentDateInt) {
nextPaymentDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDateInt);
} else {
nextPaymentDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 1);
}
console.log(nextPaymentDate);
As chŝdk says, you can write this in a lot less code, and you only need one Date. Just check the date with paymentDateInts[1], then set values accordingly:
var paymentDateInts = [1, 15];
var d = new Date();
if (d.getDate() < paymentDateInts[1]) {
d.setDate(paymentDateInts[1]);
} else {
d.setMonth(d.getMonth() + 1, paymentDateInts[0]);
}
console.log(d.toString());
If you want toget a date at the same month then use getFullYear(), getMonth() when creating a new Date:
let nextPaymentDate = new Data(currentDate.getFullYear(), currentDate.getMonth(), nextPaymentDateInt)
Else, if you need next month, then use currentDate.getMonth() + 1
You can use the setDate method. For example
let firstDateInteger = new Date();
firstDateInteger.setDate(paymentDateInts[0]);

new Date() function returns wrong value

The new date(code) returns working value,Please Help me
var cdt = new Date();
dob = "15/01/1999";//From date picker
alert(dob);
var bdy = dob.split("/");
var by = bdy[2];
var bm = bdy[0];
var bd = bdy[1];
var dob = new Date(bd, bm, by);
alert(bd+","+bm+","+by);
alert(dob);
Date format changed for new date() function:
Values return by that function:
new Date() method takes three parameters on constructor.
The order of parameters is following: year,month and day.
Something like this: var date=new Date(1999,01,01).
var cdt = new Date();
dob = "15/01/1999";//From date picker
var bdy = dob.split("/");
var by = bdy[2];
var bm = bdy[1];
var bd = bdy[0];
var dob = new Date(by, (bm-1), bd);
console.log(bd+","+bm+","+by);
console.log(dob.toLocaleDateString());
You could use JavaScript ISO Dates format that is the format: yyyy-mm-dd, see following example please:
var dString = "15/01/1999";
console.log("From date picker", dString);
var bdy = dString.split("/").reverse().join("-")
var dob = new Date(bdy);
console.log("Javascript Date" , dob);
I hope it helps you, bye.

Adding days to a date in a loop, javascript

I feel like there is something I'm missing about this, I'm trying to add 7 days to a current date, then 14, then 21. What I'm ending up with is a compounding of intervals rather than current date + 7, then current date + 14 etc.
var date = new Date();
for(var i = 0; i < 4; i++){
var tempDate = date;
var repeatson = tempDate.setDate(date.getDate() + (i*7));
var repeats = new Date(repeatson);
console.log(repeats);
}
Results in:
"2015-03-17T21:03:13.326Z"
"2015-03-24T21:03:13.326Z"
"2015-04-07T20:03:13.326Z"
"2015-04-28T20:03:13.326Z"
Rather than the desired, 24th, 31st & 8th
var tempDate = date; simply assigns a reference to date. You are not creating a copy. Similarly, setDate does not return a new date, it mutates the date itself.
One solution would be to create a copy:
var tempDate = new Date(date);
Your loop could be simplified to
var repeats = (new Date(date)).setDate(date.getDate() + (i*7))

How to filter the data using date from JSON format

I want to filter using date but the data is in JSON format. How can I filter the large dataset using date in JavaScript?
Example:
data=[{date:'22-12-2014',name:'selva'},{date:'10-10-2010',name:'raja'},{date:'11-11- 2011',name:'suresh'}]
If you simply want to filter data by time, you can look through all objects in the array like this:
var filteredData = [];
for(var index in data) {
var obj = data[index];
var date = parseDate(obj.date);
//Filter dates from 2011 and newer
if(date > new Date(2011, 0, 1))
filteredData.push(obj);
}
function parseDate(dateStr) {
var date = dateStr.split('-');
var day = date[0];
var month = date[1] - 1; //January = 0
var year = date[2];
return new Date(year, month, day);
}
//Filtered data now contains:
// [{"date":"22-12-2014","name":"selva"},{"date":"11-11- 2011","name":"suresh"}]
I am sure you could do the parse date better, by for example defining the date in a format that the Date constructor accepts.
To grab the set of elements that match a certain date you can use filter to extract them into a new array.
function getByDate(date){
return data.filter(function (el) {
return el.date == date;
});
}
var arr = getByDate('11-11-2011');
To to sort your dataset by date you need to convert your date strings to a JS date object first. That involves adjusting the date string slightly so it can be parsed properly.
function reformatDate(date) {
return arr = date.split('-').reverse();
}
var sortByDate = function (a, b) {
return new Date(reformatDate(a.date)) - new Date(reformatDate(b.date));
};
data.sort(sortByDate);
JSFiddle demo
I used date format MM/DD/YY. Here is the full example -
var data=[
{date:'02/10/2018',name:'date is 10'},
{date:'02/14/2018',name:'date is 14'},
{date:'02/16/2018',name:'date is 16'},
{date:'02/20/2018',name:'date is 20'},
{date:'02/24/2018',name:'date is 24'},
{date:'02/26/2018',name:'date is 26'},
{date:'02/30/2018',name:'date is 30'},
{date:'03/01/2018',name:'date is 01'},
{date:'03/05/2018',name:'date is 05'},
{date:'02/23/2018',name:'date is name 23'},
]
var today = new Date();
var todayTime = new Date().getTime();
var days_after_20 = new Date().setDate(today.getDate()+20);
var days_before_5 = new Date().setDate(today.getDate()-5);
var result = data.filter(function (item) {
var itemTime = new Date(item.date).getTime()
return itemTime >= days_before_5 && itemTime <= days_after_20;
})
console.log(result);
To fetch the set of elements that match a certain date you can use filter to extract them into a new array.
var tempArray= data.filter(function (d, i) {
return d >= startDate && d <= endDate;
})

Check the dates in JavaScript

I want to check two dates in java script. date format is YYYY-MM-dd.
var date1 = 2011-9-2;
var date1 = 2011-17-06;
Can anybody say how can I write condition?
If you mean that you want to compare them and your variables are strings, just use == for comparison.
var date1 = '1990-26-01';
var date2 = '2000-01-05';
if (date1 == date2) {
alert('date1 = date2')
}
else {
alert('something went wrong');
}
There are four ways of instantiating dates
var d = new Date();
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
Here is the link to complete tutorial and function of creating, comparing dates http://www.w3schools.com/js/js_obj_date.asp
If you want to compare dates , have a look at the JS date object https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date , in particular the getTime() method .
Assuming the format is YYYY-MM-dd (your second date value breaks this rule) and that they are strings...
var date1 = '2011-9-2';
var date2 = '2011-06-17';
var fields = date1.split("-");
var d1 = new Date (fields[0], fields[1]-1, fields[2]);
var fields = date2.split("-");
var d2 = new Date (fields[0], fields[1]-1, fields[2]);

Categories

Resources