How can I get next three working days in JS - javascript

I'm new to typescript. I wrote this code to get the next three working days(Sunday is not a working day). But it is not working. Can someone suggest an alternative solution?
today = new Date()
day1 = get_next_working_day(today)
day2 = get_next_working_day(day1)
day3 = get_next_working_day(day2)
function get_next_working_day(day){
const temp = new Date(day.setDate(day.getDate()+1) )
if(temp.getDay() == 0){
return get_next_working_day(temp)
}
return temp
}

When you call setDate on a date, it modifies the date object itself. So your code will always change today's date to be tomorrow. Try this instead
function get_next_working_day(day){
const temp = new Date(day);
temp.setDate(temp.getDate()+1);//Modifies temp valur
if(temp.getDay() == 0){
return get_next_working_day(temp);
}
return temp;
}

Related

Get Previous and Next Days

I am pulling varchar dates from a db table, and trying use them to get the date of both the previous day and next day. In the example below, I would have grabbed 2020-03-26 from my table. I am trying to figure out how to get both 2020-03-25 and 2020-03-27 saved as variables that I can then use. I have figured out that in order to get the date the exact format that I want I have to use the toISOString and slice off the first 10 characters, but I am unsure how to get the previous and next days, especially if a month crossover had occurred.
var tableDate = new Date('2020-03-26')
tableDate = tableDate.toISOString().slice(0,10)
Try this one:
let tableDate = new Date('2020-03-26');
// function to increment
function incrementDate(date, days) {
let result = new Date(date);
result.setDate(result.getDate() + days);
return result;
}
// funtion to decrement
function decrementDate(date, days) {
let result = new Date(date);
result.setDate(result.getDate() - days);
return result;
}
console.log(incrementDate(tableDate, 1).toISOString().split('T')[0]);
console.log(decrementDate(tableDate, 1).toISOString().split('T')[0]);
The decidedly easiest way is using dayjs.
With it set up you'd use it something like,
const tableDate = new Date('2020-03-26')
const dayBefore = dayjs(tableDate).subtract(1, 'day')
const dayAfter = dayjs(tableDate).add(1, 'day')
You can then apply .toISOString(), or you can simply use .format() to get the exact output you'd prefer from the outset.

Check If date is over a 2 weeks old

I’m trying to create a if statement that checks a date against the current date and throw a error if its less that 2 weeks old.
My current code
const moment = require('moment')
const today = moment().format()
const createdDate = '2020-07-30'
if (createdDate <= today ) {
console.log('Good')
} else {
console.log('Bad')
};
console.log(today)
Would appreciate any suggestions.
You can use moments subtract feature along with isSameOrAfter.
There is another option where you add two weeks to the createdDate and compare that today as well. Whichever makes more sense for you.
const today = moment();
const createdDate = moment("2020-08-30")
if (today.subtract(2, 'weeks').isSameOrAfter(createdDate)) {
console.log('good')
} else {
console.log('bad')
}
You can do this two ways and you can choose what suit you better. Both solution below will perfectly for your scenario.
You can simply use moment diff function by getting the difference of days in numbers and if the difference is more then or equal to 14 days then its good else it will be bad.
Using diff function
Live Demo:
var today = moment().startOf('day')
var createdDate = moment("2020-07-30", "YYYY-MM-DD").startOf('day')
var diff = today.diff(createdDate, 'days')
if (diff >= 14) {
console.log('Good')
} else {
console.log('Bad')
};
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.js"></script>
Using add function and clone function get the results
You can use add function along with clone and using startOf day function to make sure we always get the date from day start not when when performed the operation to check for comparison.
Live Demo:
let today = moment().startOf('day').format('YYYY-MM-DD') //today
let createdDate = moment('2020-07-30', 'YYYY-MM-DD').clone().add(14, 'days').startOf('day').format('YYYY-MM-DD') //created date minus two weeks
if (createdDate <= today) {
console.log('Good')
} else {
console.log('Bad')
};
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.js"></script>
You can use add feature of Moment as well.
const today = moment();
const createdDate = moment("2020-07-30")
if (createdDate.add(2, 'weeks').isSameOrAfter(today)) {
console.log('good to go!')
} else {
console.log('bad')
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js" integrity="sha256-ZsWP0vT+akWmvEMkNYgZrPHKU9Ke8nYBPC3dqONp1mY=" crossorigin="anonymous"></script>

How to compare dates to make sure Google Apps Script is only sending an alert once a day?

I have a script in a Google Sheet that is sending out an alert if a certain condition is met. I want to trigger the script to run hourly, however, if an alert was already sent out today, I don't want to send out another one (only the next day). What is the best way to achieve this?
I've tried formatting the date several ways, but somehow the only thing working for me so far is getting the year, month and day from the date object as int and comparing them separately.
function sendAlert{
var now = new Date();
var yearNow = now.getYear();
var monthNow = now.getMonth() + 1;
var dayNow = now.getDate();
var sheet = SpreadsheetApp.getActive().getSheetByName('CHANGE_ALERT');
var sentYear = sheet.getRange("R2").getValue();
var sentMonth = sheet.getRange("S2").getValue();
var sentDay = sheet.getRange("T2").getValue();
if (yearNow != sentYear || monthNow != sentMonth || dayNow != sentDay) {
sendEmail();
var sentYear = sheet.getRange("R2").setValue(yearNow);
var sentMonth = sheet.getRange("S2").setValue(monthNow);
var sentDay = sheet.getRange("T2").setValue(dayNow);
else {
Logger.log('Alert was already sent today.');
}
}
I think this solution is definitely not the best approach, but I cannot come up with another that merges the date into one. Only comparing the new Date() doesn't work, since the time of day will not necessarily be the same. If I format the date to YYYY-MM-dd, it should work, but then when I get the date again from the spreadsheet it gets it as a full date with the time again.
Requirement:
Compare dates and send an email if one hasn't been sent already today.
Modified Code:
function sendAlert() {
var sheet = SpreadsheetApp.getActive().getSheetByName('blank');
var cell = sheet.getRange(2,18); //cell R2
var date = new Date();
var alertDate = Utilities.formatDate(cell.getValue(), "GMT+0", "yyyy-MM-dd");
var currentDate = Utilities.formatDate(date, "GMT+0", "yyyy-MM-dd");
if (alertDate !== currentDate) {
sendEmail();
cell.setValue(date);
} else {
Logger.log('Alert was already sent today.');
}
}
As you can see, I've removed all of your year/month/day code and replaced it with Utilities.formatDate(), this allows you to compare the dates in the format you specified in your question. I've also changed the if statement to match this, so now we only need to compare alertDate and currentDate.
References:
Utilities.formatDate()
Class SimpleDateFormat

Trying to remove all the passed dates

I have an array with many dates, they are not in the date type but string like: "2016-08-12" for example. Then what I would like to do is to remove all dates that we already have passed. So therefor im trying to compare them to todays date and then remove it if its passed. Using typescript by the way.
my array, named datoArray, looks like this:
["2016-08-02", "2016-08-11", "2016-08-22", "2016-09-10"]
just with a lot more of the same...
then here's what I try to do:
for(var i = 0; i < this.datoArray.length; i++){
this.skoleAar = parseInt(this.datoArray[i].slice(0,4))
this.skoleMaaned = parseInt(this.datoArray[i].slice(5,8))
this.skoleDag = parseInt(this.datoArray[i].slice(8,10))
if(this.skoleAar < dagensAar){
this.datoArray.splice(i, 1);
}
if(this.skoleAar == dagensAar && this.skoleMaaned < dagensMaaned){
this.datoArray.splice(i, 1);
}
if(this.skoleAar == dagensAar && this.skoleMaaned == dagensMaaned && this.skoleDag < dagensDag){
this.datoArray.splice(i, 1);
}
}
the "dagensAar", "dagensMaaned" and "dagensDag" variables im getting from another function that works. If i "console.log" the variables it prints out int values like 2016 for the year and 8 for the month if i take from the start of the array, and for the "dagensAar", "dagensMaaned" and "dagensDag" it prints 2016 11 20, which is todays year, month and day. all is in Int type, so what im not getting here is why my "if" doesnt work? It seems like there is something wrong with the way i compare the, but i thought this was the way to compare int values?
If the dates are in ISO-8601 format then you can simply filter using Date.parse().
var dates = ["2016-08-02", "2016-08-11", "2016-08-22", "2016-09-10", "2016-12-15"];
function removePastDates(data) {
var today = new Date();
console.log('Initial state: ' + data);
var modified = dates.filter(function(dateString) {
return Date.parse(dateString) >= today;
});
console.log('Final state: ' + modified);
return modified;
}
var newDates = removePastDates(dates);
Your dates seem to be RFC compliant, meaning they can be directly fed into a new Date object. Simply compare to today and filter by that:
var today = new Date()
var futureDates = this.datoArray.filter(d => new Date(d) >= today)
(pre-ECMA6:)
var today = new Date()
var futureDates = this.datoArray.filter(function (d) {
return new Date(d) >= today;
})
I think the problem is not related to the dates.
I think the problem is that you are removing items from the array while looping the same exact array.
You should maybe try looping from the end of the array to the beginning or just save the indexes that you need to remove and later do the actual removing.
Keep in mind that when you remove an item you change the index of every item in the remaining of the array - maybe you should start removing from the greatest index so it will not confuse you.

comparing date value in inputbox using if else in javascript

my code below is in javascript, $('#date_start').change(function(){ is working fine, but when im using if else statement to compare the date inputted in my inputbox from the current date, nothing happens at all.
$(document).ready(function() {
$('#date_start').change(function(){
var startdate = $('#date_start').datepicker("getDate");
var today = new Date();
var tomorrow = today.add(2).day();
if(startdate.getTime() < today.getTime()){
document.getElementById('finish').disabled = true;
}
else{
Remove Time from both of Date and compare it.
String input = "2012/01/20 12:05:10.321";
DateFormat inputFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
Date date = inputFormatter.parse(input);
DateFormat outputFormatter = new SimpleDateFormat("MM/dd/yyyy");
String output = outputFormatter.format(date);

Categories

Resources