How to check for a specific date in an array - reactjs

I'm trying to do some error handling on an existing system. The backend can't be changed as it runs multiple systems. I'm working on moving the frontend from ASP.NET to React. I've come across a problem where I want to check if an array of objects contains a date, but the date retrieved from the backend comes as a /Date(1379282400000)/.
I've done some searches and can't find something that resembles this.
I tried this code:
if (data.some(e => new Date(parseInt(e.Date.substr(6))).toDateString() === this.state.date.toDateString()) {
// Logic
}
e.Date is the key used in the object for the dates and this.state.date is a date picked by the user. If I just do:
if (data.some(e => e.Date === "/Date(137982400000)/") {
// Logic
}
as a test, then it works fine. So, it seems to be the converting of the date to the string that breaks the function, but can't understand how to fix it.
It would be nice to fix that it checks the date as doing .getTime() will not work as it could be the same date, but different times.

So, found out that the problem came from trying to convert the DateTime from the backend inside the .some() function, but I was able to work it out.
First I create a new array containing only the date as that was what I needed to run a check against:
const dateConvertion = data.map(function(elem) {
return {
date: new Date(parseInt(elem.Date.substr(6))).toDateString()
};
});
Then I created the error handling:
if (dateConvertion.some(e => e.date === this.state.date) {
// Error Handling
}

Related

RangeError: Invalid Time Value after incorporating local storage

I'm working on a forum and using a form that the user fills out I'm storing data as an object inside an array. The data I'm storing includes the title of a topic, the message, the author and the date. That data is stored inside a topic array which I'm mapping on screen so the user can see all current topics, who created them and the date in which they were created. I also started to use localStorage so I can save my data and test to make sure everything looks good after my page refreshes.
const [topic, setTopic] = useState(() => {
const topicJson = localStorage.getItem("topic");
return topicJson ? JSON.parse(topicJson) : [];
});
const updatedTopic = [
...topic,
{
title: title,
message,
author: "Dagger",
date: new Date(),
},
];
setTopic(updatedTopic);
};
That's the code that I'm using which works as intended however when I map through the array to post the data on screen, I'm having trouble with showing the date. I'm using date-fns because it displays the date exactly how I want it.
Example: 2/19 9:39PM. That's how I want the date to look on screen and using date-fns has been the only thing I've found that makes it look that way.
{topic
.sort((a, b) => b.date - a.date)
.map(({ date }, index) => (
<tr>
{<td>{format(date, "M/dd h:mma")}</td>}
</tr>
))}
That's the code I'm using to map through the array to show the date. Before adding localStorage it worked fine. When I remove the format and show the code as date it works but including format gives me this error:
throw new RangeError('Invalid time value');
// Convert the date in system timezone to the same date in UTC+00:00 timezone.
// This ensures that when UTC functions will be implemented, locales will be compatible with them.
I think your are using Date object to store date and JSON.stringify cant handle Date object. You should to use Date method.
Easy way just save not Date object but ISO string.
date.toISOString()
And in table:
{<td>{format(parseISO(date), "M/dd h:mma")}</td>}

Get the Date from DateTime object String in JSON response from backend

I am working on a React JS project where my state is getting updated with date object string from the backend JSON response. I am getting a Date Time object in form of a string which looks like this:
createDateTime: "2022-02-08T14:17:44"
The "createDateTime" object is assigned to my react js state, but when I show that updated state in the Browser UI, I get this:
2022-02-08T14:17:44
I want to display just the date, not the time stamp that comes along with the JSON string response. Is there any method that I can use to display just the Date?
2022-02-08
I would create some helpers to show exactly what you need. How about something like this?
function DateTimeParser(date?: string) {
if (date === undefined) return date;
const dateTime = new Date(date);
const parsedDate = `${dateTime.getDate()} ${
dateTime.getMonth()
} ${dateTime.getFullYear()}`;
return parsedDate;
You can amend this to show exactly what you need.
Calling toLocaleDateString on your date value should get the result you want but first of all, you will need to parse the date you get from the server:
const parsedDate = new Date(responseDate)
const date = parsedDate.toLocaleDateString()
You can optionally pass to toLocaleDateString() the desired locale (in case you want to get the date in the format which differs from your local one)

How to sort when also using a where clause

I am currently pulling a list from a database, using the following code. The list is retrieved using a WHERE condition, however the list is returned unsorted. This is in the controller.
How can I modify this code so that the returned list is sorted alphabetically?
if (!string.IsNullOrEmpty(TargetYear))
{
ViewBag.HSID = new SelectList(db.Hotspots.Where(g => g.HSID.Contains(TargetYear)).ToList(), "ID", "HSID");
}
On several other fields I have used the following method to order, but I'm not sure how, or if I can combine this with the where clause above. The key piece is ".OrderBy(e=>e.FIELD), however this is precisely the piece I'm not sure how to integrate with the query.
ViewBag.LocalityCode = new SelectList(db.Localities.OrderBy(e=>e.LOCALITY1), "LOC_CODE", "LOCALITY1");
Other helpful bits of info:
ASP.Net MVC5
Microsoft SQL 2012
if (!string.IsNullOrEmpty(TargetYear))
{
var data =
db.Hotspots
.Where(g => g.HSID.Contains(TargetYear))
.OrderBy(e=>e.HSID)
.ToList();
ViewBag.HSID = new SelectList(data,"ID", "HSID");
}

How to ensure unique key while using Parse database

I need unique records my Parse object but due to the 'saveinbackground' a simple find() on the client didn't do the job. Even adding and setting a boolean like bSavingInbackGround and skip an additional save if true wouldn't prevent my app from creating duplicates.
Ensure unique keys is obvious very helpfull in many (multi user) situations.
Parse CloudCode would be the right way but I didn't find a proper solution.
After doing some trail and error testing I finally got it to work using Cloud Code. Hope it helps someone else.
My 'table' is myObjectClass and the field that needs to be unique is 'myKey'.
Add this to main.js an upload to Parse Server Cloud Code.
Change myObjectClass and 'myKey' to suit your needs:
Parse.Cloud.beforeSave("myObjectClass", function(request, response) {
var myObject = request.object;
if (myObject.isNew()){ // only check new records, else its a update
var query = new Parse.Query("myObjectClass");
query.equalTo("MyKey",myObject.get("myKey"));
query.count({
success:function(number){ //record found, don't save
//sResult = number;
if (number > 0 ){
response.error("Record already exists");
} else {
response.success();
}
},
error:function(error){ // no record found -> save
response.success();
}
})
} else {
response.success();
}
});
Your approach is the correct approach, but from a performance point of view, I think using query.first() is faster than query.count() since query.first() will stop as soon as it finds a matching record, whereas query.count() will have to go through the whole class records to return matching the number of matching records, this can be costly if you have a huge class.

How can I merge 2 google calendars to display events in order?

I'm trying to replace the clunky google calendar agenda view in my googlesite with a display that I create myself doing via google script.
I can get the event detail on the page ok, but I need to show multiple calendars - how do I ensure that the items go in correct order on the page, and are not grouped by calendar?
I could either:
create a temp calendar each time I run the script, merging multiple calendars (note - I can't see any create calendar option)
or dump info to a spreadsheet, and do a sort from there
or somehow loop by time, not calendar.
I think the spreadsheet one is the best option - any other thoughts?
Is there a simple way to copy in the iCal file to a spreadsheet automatically?
George
If PHP and the Zend Gdata library are an option, you can grab the calendar list feed and then loop through each calendar's events and put them into an array. Afterwards, you can sort them by start time with this:
function cmp( $a, $b )
{
if( $a->when[0]->startTime == $b->when[0]->startTime ){ return 0 ; }
return ($a->when[0]->startTime < $b->when[0]->startTime) ? -1 : 1;
}
uasort($allEvents,'cmp');
I've dealt with this a lot. Especially when sending guest list emails for events on more than one of my calendars. The function below will take an array of calendars and a start and end time and turn it into a single array of unique CalendarEvent objects.
You can run a version of the code here. You'll also find that it is commented there as well.
The sort piece is what you seem most interested in. It is contained in the byStart function. You can find more information about array sorting at the MDN Array.Sort Reference. byStart will work for any array of CalendarEvent.
Due to the listy nature of managing calendars, the iterative functions available in Javascript make this light work. MDN has more info on Iteration Methods
Here it is:
function mergeCalendarEvents(calendars, startTime, endTime) {
var params = { start:startTime, end:endTime, uniqueIds:[] };
return calendars.map(toUniqueEvents_, params)
.reduce(toSingleArray_)
.sort(byStart_);
}
function toCalendars_(id) { return CalendarApp.getCalendarById(id); }
function toUniqueEvents_ (calendar) {
return calendar.getEvents(this.start, this.end)
.filter(onlyUniqueEvents_, this.uniqueIds);
}
function onlyUniqueEvents_(event) {
var eventId = event.getId();
var uniqueEvent = this.indexOf(eventId) < 0;
if(uniqueEvent) this.push(eventId);
return uniqueEvent;
}
function toSingleArray_(a, b) { return a.concat(b) }
function byStart_(a, b) {
return a.getStartTime().getTime() - b.getStartTime().getTime();
}

Resources