Reputation: 623
I have the following switch statement function which is returning entries in an API from a set time date:
entries: {
recent: function(callback) {
return self.request(rest.get, '/timeentries', { startDate: '2016-02-15' }, function(result) {
callback(result);
});
},
This is working fine, I am getting results back from anything post 2016-02-15.
However, I don't want this to be static. I want to be able to pull a date range from when this is run.
I have the following code which returns the current week:
var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay();
var firstDay = new Date(curr.setDate(first)).toUTCString();
firstDay returns the start of the week, which is what I want to put in place of startDate: '2016-02-15'.
Question, how would I put firstDay in here, the following wont work:
entries: {
recent: function(callback) {
var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay();
var firstDay = new Date(curr.setDate(first)).toUTCString();
return self.request(rest.get, '/timeentries', { firstDate }, function(result) {
callback(result);
});
},
Upvotes: 0
Views: 59
Reputation: 11806
If you look closely the first call and compare it to your second call, your object is bad formed. They have to be a key: value
pair having startDate
as the key and the date as the value, so:
return self.request(rest.get, '/timeentries', { startDate: firstDate }, function(result) {
callback(result);
});
In the new ES6 specs { firstDate }
is a valid object that will put firstDate
as the key, BUT you need startDate
as the key instead.
Also, you don't have any variable firstDate
anywhere but a firstDay
one, hence the object will be { startDate: firstDay }
for it to work.
Also, toUTCString
returns an entire date string, like this: Sun, 12 Feb 2017 02:01:35 GMT
and you need only the YYY-MM-DD
format so looking at this answer you will need to do:
var d = new Date(),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
var firstDay = [year, month, day].join('-');
Upvotes: 1