JavaScript todays date + x, bad practice? - javascript

I'm currently working on a project that makes heavy use of dates.
Is there anything inherently wrong with doing this:
var TodayPlusSeven = new Date(new Date().setDate(new Date().getDate() + 7));
I'm not an expert with JavaScript, but this seems to work. I'm not sure of the negative effects that doing something like this can have.
Thanks.

In your current code you create 3 Date objects in the process. This is not necessary. You could just update one object to the respective day:
var TodayPlusSeven = new Date();
TodayPlusSeven.setDate( TodayPlusSeven.getDate() + 7 );

Related

Cypress API testing - Using custom commands to return a value to avoid duplicating code

First of all. I'm purposely re-learning JS/Cypress and I'm purposely starting from bedrock again, so apologies in advance.
I'm currently using Cypress for REST API testing. I am migrating tests over from an existing Ruby/Selenium framework and I want to use something similar to writing Ruby functions to clean up my code, as I am currently duplicating code.
An example:
I have a block of code that generates a date, 365 days in the past (ISOString used for a reason, in this case)
var date = new Date();
date.setDate(date.getDate() - 365)
var minDate = date.toISOString().split('T')[0]
I want to do something like
Cypress.Command.add('dateGen', () => {
var date = new Date();
date.setDate(date.getDate() - 365)
var minDate = date.toISOString().split('T')[0]
})
and call it in. In this case, I would want to call it in to my test using something like
(excuse the incorrect syntax, I'm just doing it as a like for like (Ruby/JS) illustration):
var date = cy.dateGen
However, running this in any js/cypress friendly combination falls over as Commands do not return values.
I am already set up to use commands in index.js etc, so that bit isn't causing me any problems. I am already using commands for things that don't return a value, so I know I'm doing that bit correctly.
I sorted it using the following:
Cypress.Commands.add('dateGenerator', (days) => {
var newDate = new Date();
newDate.setDate(newDate.getDate() - days)
var date = newDate.toISOString().split('T')[0]
return date
})
and then called it via
cy.dateGenerator(noOfDays)
.then((date) => {
var minDate = date
}
The bit I was missing was the
return date and I was closing the blocks off too early in my test code.

Storing the time and the Data in firebase Database

Im trying to create a JavaScript function that is storing some information in firebase Database each time it is called. One information that I want to store is the current Date and Time that the function has been called. I’ve create something on my own but the formation of the date and time isn’t quite how I want it to be. My source code of the function is the following:
function AddtoDatabase(id,title,description){
var rootRef = firebase.database().ref().child(`notifications/${id}`);
var tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
rootRef.push({
title:`${title}`,
description:`${description}`,
//time:`${new Date().toISOString().split('T')[0]}`
time:`${(new Date(Date.now() - tzoffset)).toISOString().slice(0, -1)}`
});
}
Using the source code above i get the following result from date and time:
How can I edit the code to get just
Received at:2018-03-14 09:48
Can anyone please help me?
I think that you can achieve this simply using the Date() object's native methods like getFullYear(), getFullMonth() etc.
Here's the code.
const date = new Date();
const year = date.getFullYear();
const month = date.getFullMonth() + 1 // months start from 0
const day = date.getDay()
const hour = date.getHours();
const minutes = date.getMinutes();
const time = `Received at ${year}-${month}-${day} ${hour}:${minutes}`;
You should use the moment library for the formatting: https://momentjs.com/
In particular, look at this part of the documentation: https://momentjs.com/docs/#/displaying/
So in your case you would do:
moment().format("YYYY-MM-DD hh:mm");
Also, a best practice is to store in your database the number of milliseconds since 1970/01/01, which you can obtain through the JavaScript getTime() method

SharePoint/Javascript: comparing calendar date times in javascript

I am trying to find the best approach to comparing date/times using Javascript in order to prevent double booking on a SharePoint calendar. So I load an array with items that contain each event, including their start date/time and end date/time. I want to compare the start date/time and end date/time against the start/end date/times in the object, but I am not sure how to ensure that dates will not lapse.
like:
//date that is created from user controls
var startDate = new Date(startDat + 'T' + startHour + ':' + startMin + ':00');
var endDate = new Date(endDat+ 'T' + endHour+ ':' + endMin+ ':00');
for ( var i = 0; i < allEvents.length; i++ ) {
var thisEvent = allevents[i];
//having trouble with the compare
//i have tried silly ifs like
if (thisEvent.startDate >= startDate && thisEvent.endDate <= endDate) {
// this seems like I am going down the wrong path for sure
}
}
I then tried breaking apart the loaded object into seperate values (int) for each component of the date
var thisObj = { startMonth: returnMonth(startDate), startDay: returnDay(startDate), etc
but I am not sure this isn't just another silly approach and there is another that just makes more sense as I am just learning this.
I have a similar requirement in progress but chose to solve it at the booking stage, with jQuery/SPServices.
The code is still in build (ie not finished) but the method may help.
I attach an event handler to a column, then on selection, fetch all the dates booked in the same list to an array, then display that array on a rolling 12 month cal, as below.
I'm not checking to ensure a new booking doesn't overlap but a quick scan through the array on Pre-Save would provide a strict Go/No Go option for me. Relies on client side JS though, so not going to work in a datasheet or web services context.

Date formating issue when using momentjs and bootstrap calendar

I have a function that return an array of objects that is used as parameter for a bootstrap calendar. The problem is when i create event_data.start. If i use start_date.year() in the end the calendar will not work because of invalid date. If I put 2013 (or any integer), then it works.
I used a breakpoint at that line, start_date.year() always return 2013.
var start_date = moment(reminder.start_date);
var stop_date = moment(reminder.stop_date);
var reminder_time = moment(reminder.time, 'HH:MM:ss');
while (start_date.unix() < stop_date.unix()) {
start_date = moment(start_date.year()+ '-' + start_date.month().toString() +'-'+start_date.add('days', 1).date());
event_data.start = new Date(parseInt(start_date.year()), 9, 25 - 3, 16, 0);
events_array.push(event_data); //events_array then used for calendar
}
I am thinking the start_date object is used as some kind of reference and the actual value is not passed or something. Hope you can give me an idea.
You are doing entirely too much manual string manipulation in this code. If you're using moment.js, then you should work with the API instead of working against it. Try something like this:
while (start_date.isBefore(stop_date)) {
start_date.add('days', 1);
event_data.start = start_date.clone().toDate();
events_array.push(event_data);
}
I used .clone() because I'm uncertain how you will be using the date in your object. You may find that it is not necessary depending on what you are doing.
Then there's some weirdness in your code to deal with. First, you define reminder_time but don't use it for anything, so I'm not sure why it is there.
Then, you had this line:
event_data.start = new Date(parseInt(start_date.year()), 9, 25 - 3, 16, 0);
That would be only using the year part of the start_date and hard-coding the rest to October 22 16:00. I'm not sure why at all you would do that, so I omitted it from the above code. If that's actually what you wanted to do, then do it like this instead:
event.start = start_date.clone().month(9).date(22).startOf('day').hour(16).toDate();
Here you definitely need to use .clone() because otherwise the manipulation of value would interfere with your loop logic.

Strange javascript assignment

I've worked with C# for many years but I'm pretty inexperienced when it comes to javascript so this should be an easy pick for any of you javascript wizards. I was looking through a JQuery plugin for managing cookies (https://github.com/carhartl/jquery-cookie) when I saw these two lines:
var days = options.expires, t = options.expires = new Date();
t.setDate(t.getDate() + days);
I just want to make sure I understand this correctly; is this the equivalent of:
var days = options.expires;
options.expires = new Date();
var t = options.expires;
t.setDate(t.getDate() + days);
I imagine this is an attempt to compress the code as much as possible but I admit I get confused when thinking about what the value of the variables are. Especially since options.expires can be either a javascript date object or a number of days.
Yes. The return value of an assignment is the value that was assigned.

Categories

Resources