Finding sets of dates between a set of dates in Javascript - javascript

Okay, I have a date picker on my application. The date picker lets the user select the dates of the datasets they want to view in a table. I start off with getting the current ms data and send it to the backend. So, let's just say I send to the back end, the following dates:
{
start: '2014-12-1',
end: '2014-12-7'
}
The backend send the data within those dates back to the front end and store them in a javascript array, a front end cache if you want to call it that. Next the user selects the dates:
{
start: '2014-11-3',
end: '2014-11-9'
}
We retrieve the data that falls within the dates and store them in the same array as the above. Say the user then selects the following dates:
{
start: '2014-11-22',
end: '2014-11-29'
}
We store these in the array mentioned above again. The user then finally selects the date ranges
{
start: '2014-11-1',
end: '2014-12-31'
}
Since, I have already retrieved much of the data that is between these dates already, I would like to figure out a way to grab all the dates series that fit between the first three date series that are inside the fourth selection. That way I am only retrieving the data I don't already have. Is there any existing algorithm that I can implement in javascript that I could use to find all the date series that I am missing?

Related

V-Calendar component in Vuetify; setting up events to scale across months

I'm looking for advice on the best way to store event dates in Postgres when it comes to fetching them and displaying them on an calendar. I'm using an node/expressjs backend with postgres as a data store. On the front end I'm using vue with vuetify/nuxt. Vuetify has a lot of convenient UI components, but more specifically the v-calendar component:
V-Calendar
I've got a few edge cases that I'm having a hard time wrapping my head around.
I want to be able to fetch events for the current month from the database and events that spill over from one month to the next, and to the next, etc. What is the best way to do this? How should I model my database table and fetch the records (I'm using Postgres)? An event needs a name, start and end. Should I instead store the total duration of the event in a unix timestamp and query the events by range between a given month duration (in seconds)?
Any advice would be welcome.
Store your events with their beginning and end dates in a range type
You can then use the overlap && range operator to figure out which events belong on a certain month's calendar.
For instance, if you have an event with duration column of type daterange defined as '[2020-01-01, 2020-03-31]'::daterange, it will be match the following condition:
where duration && '[2020-02-01, 2020-03-01)'
Please note that the closing ) is deliberate since that excludes the upper limit from the range (in this case, 1 March).
In case you would rather not store the start and end dates inside a range type, you can always construct one on the fly:
where daterange(start_date, end_date, '[]') && '[2020-02-01, 2020-03-01)'
The range for the current month can be calculated on the fly:
select daterange(
date_trunc('month', now())::date,
(date_trunc('month', now()) + interval '1 month')::date, '[)'
);
daterange
-------------------------
[2020-07-01,2020-08-01)
(1 row)
Or for a three-month calendar:
select daterange(
(date_trunc('month', now()) - interval '1 month')::date,
(date_trunc('month', now()) + interval '2 month')::date, '[)'
);
daterange
-------------------------
[2020-06-01,2020-09-01)
(1 row)
The way we stored and retrieved events was that every time a user scrolls in the calendar i use a method to return start_date_time for the current month and the previous and next month. For a total of 3 months. This way we catch any calendar overlap. We use laravel in the backend, but you should be able to get the general gist of the method. Our tableify method just formats data for us.
My DB structure is as follows (removing subjective data):
CREATE TABLE calendar_events (
id bigserial NOT NULL,
calendar_event_category_id int4 NOT NULL,
name varchar(512) NOT NULL,
description text NULL,
start_date_time timestamp(0) NOT NULL,
end_date_time timestamp(0) NULL,
"data" json NULL,
user_id int4 NULL,
created_at timestamp(0) NULL,
updated_at timestamp(0) NULL,
CONSTRAINT calendar_events_pkey PRIMARY KEY (id),
CONSTRAINT calendar_events_calendar_event_category_id_foreign FOREIGN KEY (calendar_event_category_id) REFERENCES calendar_event_categories(id),
CONSTRAINT calendar_events_user_id_foreign FOREIGN KEY (user_id) REFERENCES users(id)
);
My index method:
public function index(Request $request)
{
$currentDate = empty($request->filter_date) ? Carbon::now() : new Carbon($request->filter_date);
if (! empty($request->filter_date)) {
return api_response('Retrieved Calendar Events.',
CalendarEvent::tableify($request,
CalendarEvent::where('start_date_time', '>=', $currentDate->subMonth(1)->isoFormat('YYYY-MM-DD'))->where('start_date_time', '<=', ($currentDate->addMonth(2)->isoFormat('YYYY-MM-DD')))->orderby('start_date_time', 'DESC')
)
);
} else {
return api_response('Retrieved Calendar Events.', CalendarEvent::tableify($request, CalendarEvent::orderby('start_date_time', 'DESC')));
}
}
That's the way I solved the overlap problem. Every time the user scrolls the frontend checks if a month was changed, if so, it updates the calendar with the latest 3 month chunk.

Sequelize returning dates with wrong time

The database and node are set as -02:00 timezone.
When I save a register, using sequelize, it saves the register with the right date and time in its date fields. For example, if I save a register with the field moment set as '2017-01-15T23:59:59-0200' and look in the database via MySQL Workbench I will see 2017-01-16 00:00:00 in the respective column.
I can even correctly find registers and filter by date and time.
But the value returned by a find operation in the field is '2017-01-16T01:59:59.000Z', meaning it was added two hours to the answer.
How could I retrive the correct date and time from MySQL using Sequelize?
Solved by overhiding String.toJSON:
Date.prototype.toJSON = function(){ return this.toLocaleString(); }

To store and retrieve schedule from database the exact same location

I'm trying to create a class schedule here.
I know I'm not supposed to ask before trying anything, the problem is I can't think of any logic to do this.
As you can see I have a table as below
What I want to do is, I want to store the data in the database, and when I retrieve the data, I want to display it in the exact same location as the picture. Please help me out.
EDIT : I'm a beginner in programming please go easy on me
Code the PHP to create the HTML to display the schedule as it is in the image above, but without the courses. Hint: you should use a two dimensional array of days and times.
Create a two dimensional array of the schedule, using array keys that match those you created in step 1.
Write the code to put the schedule from step 2 in the display from step 1.
Create your database and a table for the schedule.
Write the code that reads the schedule from the database, discard the code that put the schedule into the display from the array.
Here is an example :
store data like this:
this is the query.
$query = "SELECT time_format(schedule,'%T') as schedule,
if(dayname(schedule)='Sunday',subject,'') as Sunday,
if(dayname(schedule)='Monday',subject,'') as Monday,
if(dayname(schedule)='Tuesday',subject,'') as Tuesday,
if(dayname(schedule)='Wednesday',subject,'') as Wednesday,
if(dayname(schedule)='Thursday',subject,'') as Thursday,
if(dayname(schedule)='Friday',subject,'') as Friday,
if(dayname(schedule)='Saturday',subject,'') as Saturday
FROM scheduleTable
WHERE schedule between '2016-7-25' and '2016-7-31 23:59'";
3.this is the result from the query
Then you can use PHP to style the table or send it to Ajax let javascript do the job.

Laravel count the IP adressess from this month

I have a visitor counter that works. Now, I need to get the results back to display them into a chart. What I have now in my controller to display them works, but the date is wrong.
This is what I have:
$select_stats = DB::table('visitor')->where('visit_date', '>', '2015-04-01')->where('visit_date', '<', '2015-04-30')->get();
foreach($select_stats as $statics) {
//change our object to an array
$statics = array();
}
return View::make('admin.home.index')->with('stats', $select_stats);
I need to get the 'stats' from the current month, so in this case month 4, but if it is may, then it needs to select automatically the stats from the 5th month.
So that is already a problem for me.
Now, I need to loop them in my blade themplate, that works... But the date is in the format
YYY-MM-DD
I don't want it displaying like that I do prefer the format:
DD/MM/YYYY
Okay, so far, so good.
I also need to count the IP's that are stored in the database. Also from THAT month.
And also need to loop and display the count.
The database model I have:
The table name is called visitor.
My blade template for the chart:
<script type="text/javascript">
var visitors = [
#foreach($stats as $stat)
['{{ $stat->date }}', 500],
#endforeach
];
</script>
Yes, this works in the script.
If you're always dealing with the current month, try this:
$select_stats = DB::table('visitor')->whereBetween('visit_date', array(date('Y-m-01'), date('Y-m-t')))->get();
the lowercase t in the date function returns the number of days in the given month (http://php.net/manual/en/function.date.php).
Simply put, to convert that date format in your template, you could echo it as the following:
{{ date('Y/m/d', strtotime($stat->date)) }};
To get the count of the IP's you could perform the same query but add replace ->get() with ->count() like so:
DB::table('visitor')->whereBetween('visit_date', array(date('Y-m-01'), date('Y-m-t')))->count();
You already have the IP field from the first query, so just echo out {{$stat->ip}}
There's always different & better ways to achieve certain results, but without context, here's a solution that works.

storing timestamp in meteor mongo collection and then displaying it

I have a simple form which when submitted enters data into a meteor mongo collection. I then output the data just submitted into another div, kind of like tweets being submitted and shown in a timeline.
I'd like to store the timestamp of when the user submitted the form into the collection and then display the 'feed' ordered by the timestamp descending, so newest first. I'm currently using moment.js to record the timestamp in the collection and then simply use that timestamp on the output, but it doesnt seem the most efficient way to do this.
I intend to have users in different time zones submitting the form and therefore would like to be able to display the timestamps submitted in UTC ordered by most recent.
Currently I have...
Template.form.events({
'submit form': function(e) {
e.preventDefault();
var insertPost = {
timestamp: moment().format('DD-MM-YY HH:mm:ss ZZ')
// some other stuff as well
};
form._id = Posts.insert(insertPost);
)};
Then this is being displayed in my post_item.html :
<template name="post-item">
<div>
<ul class="list-inline">
<li><small>{{timestamp}}</small></li>
// some other stuff too
</ul>
</div>
</template>
Is this way of storing the timestamp ok? I feel storing it in milliseconds is probably better and then formatting that on the output.
So I can change my form.events code to store
timestamp: moment.utc().valueOf(),
and this stores in milliseconds since the epoch, but how do I then convert that within the html template to display the timestamp nicely formatted?
Use moment js to display dates and times in various formats and the atmosphere package has plenty of installs.
http://momentjs.com
https://atmospherejs.com/momentjs/moment

Categories

Resources