how to set end date when select the start date? - javascript

i want to set end date depend on the balance and start date when the user select the start date,
for example if the start date is 2021-09-01 the balance is 11 so direct the end date will be 2021-09-12
i'm using DatePicer from ant Design ,
this is my code
useEffect(() => {
if (
(selectedLeaveId && selectedLeaveId === LeavesId.annualLeaveId)
) {
const start = startDate;
// this will change the start date too , i dont want that
const directEndDate = start?.add(remainingBalance, 'days');
setEndDate(directEndDate);
}
}, [selectedLeaveId, startDate, remainingBalance]);```

Strongly recommend using moment.js
https://momentjscom.readthedocs.io/en/latest/moment/03-manipulating/01-add/
You can pass date as below
let start = moment(startDate)
let end = start.add(DIFFERENCE, 'days');

The problem you are having is because you are modifying the start date object and assigning it to end. I'm not up-to-date on the specifics of moment js but I'd imagine you can do something like:
let end = moment(start).add(DIFFERENCE, 'days');
That way you'll create a new date object for end and add to that one, rather than modifying start.
As a side note, if you aren't going to change what's in the start or end variables you'd be better off writing const start ... rather than let start ... (it will prevent certain bugs from creeping in). This won't prevent you from changing the objects through their methods, it just stops you from accidentally reassigning them.

Related

Comparing date/timestamps in JS

For a website, we're scheduling promotions through metafields: start datetime, end datetime (format "2022-12-02T13:00:00+00:00"). In JS, i'm pulling those values and comparing them to the JS current time by converting to Epoch.
Is the way i'm approaching this fool-proof?
let currentEpoch = new Date(Date.now()).getTime()
let startPromotionEpoch = new Date(response.data.shop.promotion_start.value).getTime()
let endPromotionEpoch = new Date(response.data.shop.promotion_end.value).getTime()
if(currentEpoch > startPromotionEpoch && currentEpoch < endPromotionEpoch) {
// website updates
}
As far as i'm seeing, after extensive testing, this seems to work.
One issue i'm having though, is that it's currently Wintertime. This means that i have to enter my desired datetime in the metafield minus 1 hour for it to match my code. Ideally, this is covered by the code. How would i approach this?

Return the date format for date without moment.js

I can't figure out how to build a function that does this
INPUT: dateToDateFormat('16/07/2022') -> OUTPUT: DD/MM/YYYY
INPUT: dateToDateFormat('07/16/2022') -> OUTPUT: MM/DD/YYYY
The input dates will be already formatted by .toLocaleString function
Edit:
I think I was not precise enough with the output, it should literally output MM/DD/YYYY as a string, not the actual date value
A) First of all, your desired date string conversion seems to be easy (solution below) without using any package/overhead.
B) However, if you need to process it further as a JS Date Object, things become more difficult. In this case, I like to provide some useful code snippets at least which might help you depending on your usecase is or what you are aiming for.
A) CONVERSION
Seems you need a simple swap of day and month in your date string?
In this case, you do not need to install and import the overhead of a package such as date-fns, moment or day.js.
You can use the following function:
const date1 = "16/07/2022"
const date2 = "07/16/2022"
const dateToDateFormat = (date) => {
const obj = date.split(/\//);
return `${obj[1]}/${obj[0]}/${obj[2]}`;
};
console.log("New date1:", dateToDateFormat(date1))
console.log("New date2:", dateToDateFormat(date2))
B) STRING TO DATE
Are you using your date results to simply render it as string in the frontend? In this case, the following part might be less relevant.
However, in case of processing them by using a JS Date Object, you should be aware of the following. Unfortunately, you will not be able to convert all of your desired date results/formats, here in this case date strings "16/07/2022" & "07/16/2022", with native or common JS methods to JS Date Objects in an easy way due to my understanding. Check and run the following code snippet to see what I mean:
const newDate1 = '07/16/2022'
const newDate2 = '16/07/2022'
const dateFormat1 = new Date(newDate1);
const dateFormat2 = new Date(newDate2);
console.log("dateFormat1", dateFormat1);
console.log("dateFormat2", dateFormat2);
dateFormat2 with its leading 16 results in an 'invalid date'. You can receive more details about this topic in Mozilla's documentation. Furthermore, dateFormat1 can be converted to a valid date format but the result is not correct as the day is the 15th and not 16th. This is because JS works with arrays in this case and they are zero-based. This means that JavaScript starts counting from zero when it indexes an array (... without going into further details).
CHECK VALIDITY
In general, if you need to further process a date string, here "16/07/2022" or "07/16/2022", by converting it to a JS Date Object, you can in any case check if you succeed and a simple conversion with JS methods provides a valid Date format with the following function. At least you have kind of a control over the 'invalid date' problem:
const newDate1 = '07/16/2022'
const newDate2 = '16/07/2022'
const dateFormat1 = new Date(newDate1);
const dateFormat2 = new Date(newDate2);
function isDateValidFormat(date) {
return date instanceof Date && !isNaN(date);
}
console.log("JS Date Object?", isDateValidFormat(dateFormat1));
console.log("JS Date Object?", isDateValidFormat(dateFormat2));
Now, what is the benefit? You can use this function for further processing of your date format depending on what you need it for. As I said, it will not help us too much as we still can have valid date formats but with a falsy output (15th instead of 16th).
CONVERT TO DATE OBJECT BY KNOWING THE FORMAT
The following function converts any of your provided kinds of dates ("MM/DD/YYYY" or "DD/MM/YYYY") to a valid JS Date Object and - at the same time - a correct date. However, drawback is that it assumes to know what kind of input is used; "MM/DD/YYYY" or "DD/MM/YYYY". The dilemma is, that this information is crucial. For example, JS does not know if, for example, "07/12/2022" is "MM/DD/YYYY" or "DD/MM/YYYY". It would return a wrong result.
const newDate1 = "07/16/2022"
const newDate2 = "16/07/2022"
function convertToValidDateObject(date, inputFormat) {
const obj = date.split(/\//);
const obj0 = Number(obj[0])
const obj1 = Number(obj[1])
const obj2 = obj[2]
//
// CHECK INPUT FORMAT
if (inputFormat === "MM/DD/YYYY") {
return new Date(obj2, obj0-1, obj1+1);
} else if (inputFormat === "DD/MM/YYYY") {
return new Date(obj2, obj1-1, obj0+1);
} else {
return "ERROR! Check, if your input is valid!"
}
}
console.log("newDate1:", convertToValidDateObject(newDate1, "MM/DD/YYYY"))
console.log("newDate2:", convertToValidDateObject(newDate2, "DD/MM/YYYY"))
console.log("newDate2:", convertToValidDateObject(newDate2, "MM/YYYY"))
If the wrong format is provided as a second argument, an error is provided in the console. In practise I suggest you to use a try-catch block ( I tried here, but it does not work here in this stackoverflow editor).
I wish you good luck. Hope these information can help you.

Node.JS V12 Trello API How to check to see if a card is overdue

I am using Node.js V12 with the the trello-node-api package installed. I am able to find all the cards in a list but when I was looking through the json API for the card Link Here I am not able to find the correct title to check to see if the card is over due. I can find if the date was completed but not when the date turns red (Which is what I want) . I am very new with Javascript and I am not sure how to check for the red due date.
Pretty much to sum it up: I dont know how to check to see if a card is over due or not.
Here is the code that I came up with so far
Const trelloNode = require("trello-node-api")("privateinfo")
trelloNode.board.searchCards(boardID).then(function(response) {
response.forEach(element => {
if (element.idList === myListId2) {
var cardLink = element.shortLink;
if () {
//if the card shows the "red due date"
}
}
})
})
```
So I basiclly awnsered my own question.
What I did is added two if statements.
The first one is checking to see if the card even has a due date. The second one is checking the current time against the due date. As I am new to javascript, this may not be the best way but this is my way.
var date1 = element.due;
var date4 = new Date("1970-01-01T00:00:00.000Z") // Reason is because cards that have no due date go back to this date so I have to exclude it.
var date2 = new Date(date1);
var date3 = new Date();
if (date2.getTime() != date4.getTime()){ // Checking to see if a card has a due date
if (date2.getTime() <= date3.getTime()){ // Checking for over due's

Avoid choosing previous dates before today, without including today from datapicker on JS and React

I am intending to use a datapicker that does not allow the user to choose previous days before today, but I do want that today itself is available. I did this:
<input
name = "availabilityFrom"
onChange = {(e) => handleDateIn (e.target.value, e.target.name)}
type = "date"
/>
I am working with React so this above is part of a component, that has a state. Then with the value taken, I stored it on a variable to use its valueOf (), and created today´s variable also. Please notice that this.state.filterBy.availabilityFrom holds the value of the target, the selected date on the datapicker.
let today = new Date().valueOf();
let availabilityFromToDate = new Date(this.state.filterBy.availabilityFrom.split("-").join(",")).valueOf();
Then I used a conditional statement to get the desired behavior of the alert:
if (availabilityFromToDate <today && availabilityFromToDate)
{
sweetAlert ("Warning!",
"The entry date must be after the current date";
"warning");
}
It works well, I got so happy when it did. But if I choose today's date, I got the alert message anyway, even if I am not using <= for today.
Maybe I am not understanding the proper use of valueOf (). Been having nightmares about this, haha.
Thanks in advance!: D

moment.js errors

I'm trying to replace the functions that I had previously built with date.js, using moment.js. I'm wrapping the dates in moment wrappers like this:
var start = moment(new Date(lastLoadDate.getTime()));
var end = moment(new Date(lastLoadDate.getTime()));
Then, I'm trying to set Datepicker values based upon lastLoadDate. So, for last month, I'm doing:
start = start.day(1);
end = end.day(1).add('months', 1).subtract('days', 1);
// format dates and set DatePicker values
start = start.format('MM/DD/YYYY');
$('.date_from', context).val(start);
end = end.format('MM/DD/YYYY');
$('.date_to', context).val(end);
This gives me my first error:
end.day(1).add is not a function
However, if I take out part of the end date manipulation
end = end.day(1);
I now get the error:
start.format is not a function
I'm using moment.min.js version 1.1.0.
Turns out that the documentation is wrong, and that function date() should be used instead of day() to set the date. Instead of writing
end = end.day(1).add('months', 1).subtract('days', 1);
either
end = end.date(1).add('months', 1).subtract('days', 1);
or
end.date(1).add('months', 1).subtract('days', 1);
will work, interchangeably.

Categories