Google App Scripts - Getting a constant "Yesterday" - javascript

I'm trying to set a const "Yesterday" but the script is not recognised as a function (I'm using Google App Scripts).
I've tried different syntax including:
const yesterday = today.setDate(-1);
and
const yesterday = new Date(today.setDate(-1));
But neither worked.
I'm pretty sure it should be a minor change but I cannot figure out how to solve this.
A little help would be highly appreciated, thanks !
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName('My Report');
function insertColumn() {
const range = sheet.getRange('H1:H69').getValues();
const newrange = sheet.getRange('I1:I69');
const rules = sheet.getConditionalFormatRules();
const today = Utilities.formatDate(new Date(), "GMT+7", "MM/dd/yyyy");
const yesterday = new Date(today.setDate(-1));

Your issue is that today is not a Date object, because you've called Utilities.formatDate on it. This is why you are getting an error when trying to use today.setDate(). So you need to use another variable to allow you to compute yesterday. For example:
const tmp = new Date();
const yesterday = new Date(tmp.setDate(tmp.getDate()-1))
Also note that setDate(-1) sets the date to the penultimate day in the previous month (e.g. March 30 when you are in April), you need to get the current date (using getDate) and subtract 1 from that to get yesterday's date.

getYesterday() {
let date = new Date();
let yesterday_milliseconds = date.getTime() - 1000 * 60 * 60 * 24;
let yesterday = new Date();
yesterday.setTime(yesterday_milliseconds);
let strYear = yesterday.getFullYear();
let strDay = yesterday.getDate();
let strMonth = yesterday.getMonth() + 1;
if (strMonth < 10) {
strMonth = "0" + strMonth;
}
if (strDay < 10) {
strDay = "0" + strDay;
}
return strYear + "-" + strMonth + "-" + strDay;
},

function yesterday() {
let dt = new Date();
Logger.log(new Date(dt.setDate(dt.getDate() - 1)));
}
From MDN setDate() returns: The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date... not a date object

Related

Unable to loop through the Min attribute of HTML Date picker

I am working on something in which I should be able to choose the date with having a 3 days gap from current date. Also, the weekend should be excluded from the 3 days of gap. I was able to do the first task and lost with the logic to proceed the second. I am aware of using date.getDay() but I am lost for building up the algorithm. Please explain where should I construct.
const addDate = 7;
const min = new Date(Date.now() + (addDate * (24 * 60 * 60 * 1000)));
const year = min.getFullYear();
const month = (min.getMonth() + 1).toString().padStart(2, '0');
const day = min.getDate().toString().padStart(2, '0');
//const weekend = min.getDay();
//console.log("weekend is "+weekend);
const minDate = `${year}-${month}-${day}`;
document.getElementById("dateAve").setAttribute("min", minDate);
Here's how I would go about it.
I explained my reasoning as comments in the code
let datesAdded = 0; // For keeping track of the number of times we've changed the date
const maxDatesToAdd = 3; // Number of extra days you want to add to today
const weekends = [0, 6]; // indices of weekends you get from Date.getDay();
let date = new Date();
console.log(`Today: ${date}`);
while (datesAdded < maxDatesToAdd) {
const newDate = new Date(date.getTime() + (24 * 60 * 60 * 1000));
date = newDate; // Changing the date to newDate
if (weekends.includes(newDate.getDay())) continue; // Checking if the day we've added is a weekend
datesAdded++; // Incrementing if the day isnt a weekday and for the while loop to eventually break
}
console.log(`3 days from today without weekends: ${date}`);
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
const minDate = `${year}-${month}-${day}`; // Converting the date to a the YYYY-MM-DD format.
console.log(minDate);

Current Date converted to 10 days before and 10 days after

I have this code where I convert the current date to this format 2020-08-20 . But how do I alter it to give me the date 10 days from today and 10 days before today.
eg today is 2020-08-20 I am trying to get 10 days from today 2020-08-30
This is my code
const dateConverter = (dateIn) => {
var year = dateIn.getFullYear();
var month = dateIn.getMonth() + 1; // getMonth() is zero-based
var day = dateIn.getDate();
return year + "-" + month.toString().padStart(2, "0") + "-" + day.toString().padStart(2, "0");
}
var today = new Date();
console.log(dateConverter(today));
It's a little bit tricky. First set the hours from the date to 12 for avoiding problems with summer/wintertime-changing. Then use getDate add 10 for the extra days and setDate with the new value. Now you have a value in milliseconds, generate out of this a new date to get an dateobject. For the second date subtract 20 days because the original date was changed by the action before and do all other the same.
Format the output for the dates with getFullYear, getMonth and getDate
. Because month is handled in JS from 0 to 11 add 1 month. Months and days could be 1-digit but you want it 2 digits, so add before the string "0" and get the last 2 chars of it with slice.
Do the format for both dates and return them as array.
const dateConverter = (dateIn) => {
dateIn.setHours(12);
let dateIn10days = new Date(dateIn.setDate(dateIn.getDate() + 10));
let dateFor10days = new Date(dateIn.setDate(dateIn.getDate() - 20));
let strIn10Days = dateIn10days.getFullYear() + '-' + ('0' +(dateIn10days.getMonth()+1)).slice(-2) + '-' + ('0' + dateIn10days.getDate()).slice(-2);
let strFor10Days = dateFor10days.getFullYear() + '-' + ('0' +(dateFor10days.getMonth()+1)).slice(-2) + '-' + ('0' + dateFor10days.getDate()).slice(-2);
return [strFor10Days, strIn10Days];
}
let today = new Date();
console.log(dateConverter(today));
Try this
const dateConverter = (dateIn) => {
var year = dateIn.getFullYear();
var month = dateIn.getMonth() + 1; // getMonth() is zero-based
var day = dateIn.getDate();
return year + "-" + month.toString().padStart(2, "0") + "-" + day.toString().padStart(2, "0");
}
var today = new Date();
var numberOfDaysToAdd = 10;
var tenDaysPlus = today.setDate(today.getDate() + numberOfDaysToAdd);
console.log(dateConverter(today));
var today = new Date();
var numberOfDaysToSubtract = 10;
var tenDaysMinus = today.setDate(today.getDate() - numberOfDaysToSubtract);
console.log(dateConverter(today));
I would suggest you to use the moment library but you still want plain javascript
const convert = (date) => {
const pastDate = new Date(date)
pastDate.setDate(pastDate.getDate() - 10);
const futureDate = new Date(date)
futureDate.setDate(futureDate.getDate() + 10);
return { pastDate, futureDate }
}
call convert function with any date.
This code will help you
Reference JavaScript calculating date from today date to 7 days before
for after 10 days just just convert the - to +
const dateConverter = (dateIn) => {
var dates ={};
var days = 10; // Days you want to subtract
for(let i=0;i<days;i++){
var date = dateIn;
var last = new Date(date.getTime() - (i * 24 * 60 * 60 * 1000));
var day = last.getDate();
var month= last.getMonth()+1;
var year= last.getFullYear();
dates[i] = year + "-" + month.toString().padStart(2, "0") + "-" + day.toString().padStart(2, "0");
}
return dates
}
var today = new Date();
console.log(dateConverter(today));
I've been messing around that before as well.
But on this Stack Overflow you can find a really good answer:
Add days to JavaScript Date
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
var date = new Date();
alert(date.addDays(5));
This is the code taken from that post.
For subtracting days, just replace the "+ days" with "- days"
Hope this solved your problem!
You can convert all the dates to timestamp and then simply calculate with them:
const dateTimestamp = new Date("2020-10-10").getTime()
const milisecondsInADay = 60*60*24*1000
const milisecondsInTenDays = milisecondsInADay * 10
const beforeDate = new Date(dateTimestamp - milisecondsInTenDays)
const afterDate = new Date(dateTimestamp + milisecondsInTenDays)
console.log("before", beforeDate)
console.log("after", afterDate)
console.log("initially", new Date(dateTimestamp))

Timestamp difference in seconds

I need difference of two timestamp in seconds. But when calculate it gave wrongly. How to calculate the seconds from difference of two timestamp? Thanks in advance.
Here,
First timestamp = 20180104113612
Second timestamp = 20180104113954
Difference = First timestamp - Second timestamp
It results as 342. But actually it should be 222. So please anyone help to find the difference in seconds?
You need to parse out year, month, day, hour, minutes and seconds from your date and create a date object and then subtract both dates to get the difference.
var firstTimestamp = 20180104113612,
secondTimestamp = 20180104113954,
getDate = (time) => {
time = time.toString();
var year = time.substring(0,4),
month = time.substring(4,6),
day = time.substring(6,8),
hour = time.substring(8,10),
minutes = time.substring(10,12),
seconds = time.substring(12,14);
return new Date(year, month, day, hour, minutes, seconds);
},
getTimeDifference = (firstTime, secondTime) => {
return Math.floor((getDate(secondTime) - getDate(firstTime))/1000);
};
console.log(getTimeDifference(firstTimestamp, secondTimestamp));
Try this
let startDate = new Date();
let endDate = new Date();
let differenceInSecond = (endDate - startDate) / 1000; //since it's originally in milliseconds
first you have to format your date in proper format something like this. "2018-01-04T11:36:12";
for formatting you can use make some function like this
function getFormat(dateString) {
var txt = dateString.slice(0, 4)
+ "-"
+ dateString.slice(4, 6)
+ "-"
+dateString.slice(6,8)
+"T"
+dateString.slice(8,10)
+":"
+dateString.slice(10,12)
+":"
+dateString.slice(12,14);
return txt;
}
and then convert it into javascript Date object.
const First_timestamp = 20180104113612;
const Second_timestamp = 20180104113954;
const FirstDate = new Date(getFormat(First_timestamp.toString()));
const SecondDate = new Date(getFormat(Second_timestamp.toString()));
const TimeDiffInSeconds = (SecondDate.getTime() - FirstDate.getTime()) / 1000;

Find out how many days till next birthday and previous birthday - javascript [duplicate]

I tried this but it fails
var diffDays1=(function(){
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var secondDate = new Date(new Date().getFullYear()+1,4,5);
var firstDate = new Date();
return Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
})();
Wolfram alpha says it's 330 days, diffDays1 shows it's 359. This is probably due to daylight savings or something. Is there a way to accurately calculate days since without doing it server side.
The problem is that you're basing the month on April being 4, when April is 3 in Javascript. See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date#Parameters
var diffDays1=(function(){
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var secondDate = new Date(new Date().getFullYear()+1,3,5);
var firstDate = new Date();
return Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
})();
Why reinvent the wheel??
Use datejs
and after:
var startd = Date.parseExact(ind, "yyyy-MM-dd");
var endd = Date.parseExact(end, "yyyy-MM-dd");
var diff = new Date(endd - startd);
var days = diff/1000/60/60/24;
That's all folks!
The moment.js library (http://momentjs.com) handles this and a lot of other JavaScript date issues very easily and nicely. The diff function (http://momentjs.com/docs/#/displaying/difference/) will do exactly what you want.
The fromNow function is also super nice if want to display the number of days from now you could do something like:
moment([2014, 4, 5]).fromNow();
would produce something like "330 days" if it's 330 days away.
http://momentjs.com/docs/#/displaying/fromnow/
Here's a cleaner solution using moment, which handles all cases correctly (including today, upcoming birthday this year or not until next year, time zone, leap year, etc.):
const birthdate = '2018-12-15';
const today = moment().format('YYYY-MM-DD');
const years = moment().diff(birthdate, 'years');
const adjustToday = birthdate.substring(5) === today.substring(5) ? 0 : 1;
const nextBirthday = moment(birthdate).add(years + adjustToday, 'years');
const daysUntilBirthday = nextBirthday.diff(today, 'days');
Simple, fast, accurate!
Here's the same code, explained:
// This is the birthdate we're checking, in ISO 8601 format
const birthdate = '2018-12-15';
// Get today's date in ISO 8601 format
const today = moment().format('YYYY-MM-DD');
// Calculate current age of person in years (moment truncates by default)
const years = moment().diff(birthdate, 'years');
// Special case if birthday is today; we do NOT need an extra year added
const adjustToday = birthdate.substring(5) === today.substring(5) ? 0 : 1;
// Add age plus one year (unless birthday is today) to get next birthday
const nextBirthday = moment(birthdate).add(years + adjustToday, 'years');
// Final calculation in days
const daysUntilBirthday = nextBirthday.diff(today, 'days');
If the birthday is today, the result will be 0; if it is tomorrow, the result will be 1, and so on.
The selected solution doesn't work if the birthday is this year, because it sums 1 to getFullYear.
This is my solution, it also prevents two edge cases: birthday today and 1 day remaining.
const birthdayDay = 19;
const birthdayMonth = 11; // december === 11
const myBirthdayThisYear = new Date(new Date().getFullYear(), 11, 19).setHours(23, 59, 59);
export const daysUntilBirthday = () => {
const addToYear = myBirthdayThisYear > Date.now() ? 0 : 1;
const oneDay = 24 * 60 * 60 * 1000;
const secondDate = new Date(new Date().getFullYear() + addToYear, birthdayMonth, birthdayDay);
const firstDate = new Date();
const days = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime()) / (oneDay)));
const daysOrDay = days === 1 ? 'day' : 'days';
return days !== 365 ? `${days} ${daysOrDay} until my birthday 😉😉` : '🎂 TODAY IS MY BIRTHDAY 🎂';
};

Get last week date with jQuery/Javascript

I'm trying to get the last week date in JavaScript, without the time.
So for example, 10-02-2012, instead of 10-02-12 13:34:56 GMT.
Is there an easy solution out there for this?
Thank you!
Edit:
I'm trying to make this dynamic, so that the resulting variable is always one week before the current date. Here's what I've done to calculate the today variable, if this helps or can be used!
var currentTime = new Date();
var month = currentTime.getMonth() + 1
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var today = month + "-" + day + "-" + year;
alert(today)
I prefer something like this
​
function getLastWeek() {
var today = new Date();
var lastWeek = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 7);
return lastWeek;
}
var lastWeek = getLastWeek();
var lastWeekMonth = lastWeek.getMonth() + 1;
var lastWeekDay = lastWeek.getDate();
var lastWeekYear = lastWeek.getFullYear();
var lastWeekDisplay = lastWeekMonth + "/" + lastWeekDay + "/" + lastWeekYear;
var lastWeekDisplayPadded = ("00" + lastWeekMonth.toString()).slice(-2) + "/" + ("00" + lastWeekDay.toString()).slice(-2) + "/" + ("0000" + lastWeekYear.toString()).slice(-4);
console.log(lastWeekDisplay);
console.log(lastWeekDisplayPadded);
And if you're using jQuery UI, you can do this instead of the manual steps to build the string
var lastWeekDisplay = $.datepicker.formatDate('mm/dd/yy', getLastWeek());
Or for today
var todayDisplay = $.datepicker.formatDate('mm/dd/yy', new Date());
var firstDay = new Date("2009/10/02");
var previousweek= new Date(firstDay.getTime() - 7 * 24 * 60 * 60 * 1000);
Check out this link. It will help:- http://code.google.com/p/datejs/
We can't have a javascript date question answered without mentioning Moment.js.
moment().subtract('days', 7).format('MM-DD-YYYY')
Possible without external dependencies
new Date().setDate(new Date().getDate() - 7)
If you really want to create this from a full timestamp like 10-02-12 13:34:56 GMT, you might want to do this:
var time = '10-02-12 13:34:56 GMT';
document.write(time.substr(0,7));
use this code to subtract any number of days as i have selected 9 it will give last 10 days result including today
var date = new Date();
var day=date.getDate();
var month=date.getMonth() + 1;
var year=date.getFullYear();
var startDate=day+"/"+month+"/"+year;
var dayBeforeNineDays=moment().subtract(9, 'days').format('DD/MM/YYYY');
startDate=dayBeforeNineDays;
var endDate=day+"/"+month+"/"+year;
function getLastWeek() {
let today = new Date();
let day = today.getDay();
let t = day-1;
let monday = new Date(today.getFullYear(), today.getMonth(), today.getDate() - t - 7); //monday from last week
let sunday = new Date(today.getFullYear(), today.getMonth(), today.getDate() - t - 1); //sunday from ast week
return [monday, sunday];
}
var last_week = getLastWeek();

Categories

Resources