Why Would Date Change give me This Error Code? - reactjs

I have this code that connect to an API. It uses the current month and year to do a query of data. When the month was Aug, and it used the number 8 for ${month}, all worked perfectly. Now that it is Sept, and it uses 9 for ${month}, it returns "request failed with status 400". But if I set it back to 8, it works perfectly again. Any idea why this would be the case?
Getting Date and Setting Path based on date:
const date = new Date();
console.log(date);
const year = date.getFullYear();
let month = date.getMonth() + 1;
const path = `/v2/reports/time/team?from=${year}0${month}01&to=${year}0${month}31`;
Then this call, worked perfectly throughout the month of Aug, when month was 8. Now in Sept, month changes to 9, and I get status 400. Why?
Variables for API call:
const https = require('https');
const options = {
protocol: "https:",
hostname: "api.xxxxx.com",
path: path,
headers: {
"User-Agent": "PPR Profile",
"Authorization": "Bearer " + "xxxxxxxxx",
"Harvest-Account-ID": "xxxxxxxx"
}
}
Actual Call:
When I manually set month to 8, console log shows exactly the data I want. When manually set month to 9, i get the error 400 code.
let teamBillableData = [];
let teamMemberBillableAmount = 0;
let teamMemberIndex = 0;
https.get(options, (res) => {
const { statusCode } = res;
if (statusCode !== 200) {
console.error(`Request failed with status: ${statusCode}`);
return;
}
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; });
res.on('end', () => {
try {
const parsedData = JSON.parse(rawData);
for (let i = 0; i < parsedData.results.length; i++){
console.log(`${parsedData.results[i].user_name} billable: $${parsedData.results[i].billable_amount}`);
}
console.log(parsedData.results);

As Dave hints at, your API may require valid dates. There are only 30 days in September and your end date is set to 31 for all requests.
You will also need to fix where the code appends 0 to the month as it will create three digit months for October, November, and December.

Related

so I'm using moment.js to find the time difference from the time coming from the Backend(UTC) and the local time gotten from moment.js

Now my code works and i get the right time in Local host. The problem is why am i getting an additional 5 hours added in when viewed from the developer portal, is it an env issue ? config issue? what's happening?
below shows is me calculating how much hours/days/months ago has a certain notification been received
const getDayDiff = (timestamp) => {`enter code here`
let a = moment.utc();
console.log("from moment", a);
let b = moment(timestamp);
console.log("from backend", b);
let temp = ["year", "month", "days", "hour", "minute", "second"];
let i = 1;
do {
let diff = a.diff(b, temp[i]);
if (diff !== 0) {
return `${diff} ${temp[i]} ago`;
}
i = i + 1;
} while (i <= temp.length);
};
and how it'll look when u console loh them

Convert datetime to timestamp milliseconds adding +1 month

high chart not rendering in IE and Safari, and solution for this problem is converting my date from API to time stamp in milliseconds.
here is code for convert
var date = '2017-06-07 10:00:00'
var d = date.match(/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/)
console.log(d)
var parsed = +(new Date(d[1], d[2], d[3], d[4], d[5], d[6]).getTime())
console.log("timestamp: " + parsed) // 1499414400000 ==> July 7, 2017 8:00:00 AM
But I allways get +1 month
here is example
js fiddle
This is because the moth count start with zero you can see here the full explanation:
https://www.w3schools.com/jsref/jsref_getmonth.asp
Hello Please check it out this can be your perfect solution
const date = '2017-06-07 10:00:00'
const d = date.match(/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/)
var dates = new Date(d[0])
const parsed = new Date(dates).getTime()
Highcharts.stockChart('container', {
series: [{
data: [[parsed, 10]]
}]
});
thnx to all, here is how I fix this.
var date = '2017-06-07 10:00:00'
var d = date.match(/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/)
var parsed = new Date(d[1], d[2]-1, d[3], d[4], d[5], d[6]).getTime() //I added -1 for month
Highcharts.stockChart('container', {
series: [{
data: [[parsed, 10]]
}]
});

Exact Time Ago is not coming form moment js

I am doing my project in reactjs and i want time ago to show in table.i am using moment js to show time ago(fromNow()) but it shows the time few second only when the data comes from server.And it shows directly 6hrs ago if the data are not coming from server.Eg afer 2minutes of time interval it shows 6 hours ago.As shown in table below.
the code of my project is shown below
componentDidMount() {
let socket = new WebSocket('wss://api.example.com.np/ws');
this.setState({ socket: socket,noOfVehicle:this.state.supportInfo.length });
this.getSupportInfo();
socket.onmessage = ((message) => {
let socketData = JSON.parse(message.data);
let device_id = socketData[0].device_id;
let updatedSupportInfo = this.getUpdatedInfo(this.state.sourceName);
let flag = true;
let uSupport = updatedSupportInfo.map(function(item){
if(device_id == item.device_id){
item.current_pos = socketData[0].current_pos;
if(item.current_pos){
flag = true;
item["latlng"] = item.current_pos.x + ',' + item.current_pos.y;
}else{
flag = false;
}
let time = new Date(socketData[0].timestamp);
let now = new Date();
let timeAgoIn = moment(time).fromNow(true);
item["timeAgoIn"] = timeAgoIn;
}
getSupportInfo() {
axios({
method: 'get',
url: 'https://support.taranga.com.np/support_info'
})
.then((response) => {
for (var i = 0; i < response.data.length; i++) {
if(response.data[i].current_pos){
response.data[i]["latlng"] = response.data[i].current_pos.x + ',' + response.data[i].current_pos.y;
let time = new Date(response.data[i].timestamp)
let now = new Date();
let a = moment(time);
let b = moment(now);
let timeAgo = b.diff(a, 'hours')
let timeAgoIn = moment(time).fromNow(true)
response.data[i]["timeAgo"] = timeAgo;
response.data[i]["timeAgoIn"] = timeAgoIn;
}
}
this.setState({
supportInfo: response.data
});
})
.catch((error)=>{
throw (error);
});
}
getUpdatedInfo(name) {
let uInfo = [];
let tempSupport = this.state.supportInfo.slice();
_.map(tempSupport,(value,key) =>{
if(value.timeAgo !=0){
let time = new Date(value.timestamp)
let now = new Date();
let a = moment(time);
let b = moment(now);
let timeAgo = b.diff(a, 'minutes')
console.log(timeAgo);
//let timeAgo = moment.duration(b-a).humanize()
let timeAgoIn = moment(time).fromNow(true)
value["timeAgo"] = timeAgo;
value["timeAgoIn"] = timeAgoIn;
}
});
this.setState({
supportInfo:tempSupport
});
the code to show in table is
<TableHeaderColumn dataField="timeAgoIn" dataSort={true}>Time Ago</TableHeaderColumn>
I believe your logic is flawed, when you get the info you are storing the timeAgo once, however timeAgo is a property that changes over time, ex:
You receive a message at 12:00, you set timeAgo to 1 second (or w/e js sets it to)
You check your screen at 12:05, timeAgo for that message is still 1 second, because this is calculated once, but time has passed and timeAgo should be 5 seconds ago, right?
timeAgo property should remain as the timestamp you received from server and be calculated when you refresh your table (when you want to do this is a different topic)

How do you find all Users *not* in a Parse.com Query?

I have a "Logs" table that has a pointer to a User in the User table. I am trying to "Find all users without a log entry for the last N days". The following query, however, seems to return all users instead of the expected value.
Here is my current query:
var logsFrom = function(start, end) {
// Query for all logs within the last 24 hours
var Log = Parse.Object.extend("Log");
var query = new Parse.Query(Log);
query.greaterThanOrEqualTo("createdAt", start);
query.lessThan("createdAt", end);
return query;
};
var nonLogsFound = function(request, response) {
Parse.Cloud.useMasterKey();
// Midnight of the current day
var end = new Date();
end.setHours(0, 0, 0, 0);
// Midnight of the previous day
var time = (5 * 24 * 3600 * 1000);
var start = new Date(end.getTime() - (time));
var count = 0;
var logQuery = logsFrom(start, end);
var userQuery = new Parse.Query(Parse.User);
userQuery.doesNotMatchKeyInQuery("objectId", "user", logQuery);
userQuery.find({
success: function(users) {
// This returns *all* users.
count = users.length;
response.success("Query complete! (" + count + " results)");
},
error: function(error) {
console.error(error);
response.error(error);
}
});
};
Thanks
Your query is matching an pointer ('user') against a string ('objectId'). That is why it's returning all results.
Maybe changing
userQuery.doesNotMatchKeyInQuery("objectId", "user", logQuery);
To
userQuery.doesNotMatchKeyInQuery("objectId", "user.objectId", logQuery);
I'm not sure if it supports keypaths though haven't tested.

How to get data from mongoDB based on date from express.?

I am trying to get data from mongoDB collection based on the date it is created.
Date format using to get data: yyyy-mm-dd (eg: 2015-04-14)
Format saved in collection : timestamp: "2015-04-13T17:50:48.761Z"
Controller :
$scope.getExpences = function (date) {
SelectedMemberExpence.get( date )
.success(function (result) {
$scope.allExpences = result;
})
}
Service :
.service('SelectedTimeExpence', function ($http) {
return {
get : function(datetime) {
return $http.get('/api/expences/'+ datetime);
},
delete : function(datetime) {
return $http.delete('/api/expences/'+ datetime);
}
}
})
Express code :
router
.param('datetime', function (req, res, next) {
req.dbQuery = { timestamp : req.params.datetime };
next();
})
.route('/expences/:datetime')
.get(function (req, res) {
var collection = db.get('memberExpences');
collection.find(req.dbQuery , function (err, data) {
res.json(data);
});
});
I know, I am doing something wrong in 'express' code function. Please help anyone to resolve this problem.
The timestamp field in your collection is of string type which resembles an ISO date timestamp string. The query will certainly not work because you will be comparing two completely different strings (based on length, the timestamp field has more characters than the datetime req parameter value).
Would be much easier if you were to include another field in your document schema that actually represents a date:
db.collection.find().forEach(function (doc){
doc.created_on = ISODate(doc.timestamp);
db.collection.save(doc);
});
You can then use a range query to search for documents whose value for the created_on field is greater than a Date object representing the start of the datetime variable day, and less than a Date object representing the datetime variable day end.
First you need to construct the Date objects representing the start and end of the datetime day. For example:
var datetime = "2015-04-14",
start = new Date(datetime),
dateParts = datetime.split('-'),
y = parseInt(dateParts[0], 10),
m = parseInt(dateParts[1], 10),
d = parseInt(dateParts[2], 10),
end = new Date(y, m-1, d+1);
console.log(start.toISOString()); // "2015-04-14T00:00:00.000Z "
console.log(end.toISOString()); // "2015-04-15T00:00:00.000Z"
In your Express code you can then modify it to reflect the above:
router
.param('datetime', function (req, res, next) {
var start = new Date(req.params.datetime),
dateParts = datetime.split('-'),
y = parseInt(dateParts[0], 10),
m = parseInt(dateParts[1], 10),
d = parseInt(dateParts[2], 10),
end = new Date(y, m-1, d+1);
req.dbQuery = {"created_on": { $gte: start, $lt: end }};
next();
})
.route('/expences/:datetime')
.get(function (req, res) {
var collection = db.get('memberExpences');
collection.find(req.dbQuery , function (err, data) {
res.json(data);
});
});
Note the use of the special $ operators, $gte (greater-than-or-equal) and $lt (less-than), which are used to perform a range query to get the matching documents.
Using MomentJS:
var start = moment("2015-04-14").format();
var end = moment(start).add('days', 1);
db.collection.find({"created_on": {"$gte": start, "$lt": end}});
EDIT
In node, the Mongo driver will give you an ISO string, not the object thus if you want to include an additional created_on field in your document, simply add a new field with the current date value. For example:
.post(function (req, res) {
var date = new Date();
var expence = req.body;
expence["created_on"] = date;
var collection = db.get('memberExpences');
collection.insert(expence, function (err, data) {
res.json(200);
});
});
A little change I had to use with the above answer that I want to share with you
var start = moment("2020-04-14").format();
db.collection.find({"created_on": {"$gte": new Date(start)}});

Resources