How to build a date from separate data with google app script? - google-apps-script

In my first sheet I have this:
E21: 1 juin 2020
G21: 09
H21: h
I21: 02
I want to keep this in the first sheet but In the second sheet I want this:
B3: 2020-06-01 09:02
I try this:
// I recover my sheet
var ss_evenement = SpreadsheetApp.getActive().getSheetByName('Evenement');
// I get my date
var dateDebut = ss_evenement.getRange('E21').activate().getValue();
// I put my date in sting
var dateDebutSTR = dateDebut.toString();
// I found the day of my date : with getDay I have the day of the week
var jourDebut = dateDebutSTR.substring(8,10);
// I found the month
var moisDebut = dateDebut.getMonth().toString();
// I found the Year
var anneeDebut = dateDebut.getYear().toString();
// I read the hours
var heureDebut = ss_evenement.getRange('G21').activate().getValue();
// I read the minutes
var minuteDebut = ss_evenement.getRange('I21').activate().getValue();
// I recreate my date
var dateheureDebut = new Date(anneeDebut, moisDebut, jourDebut, heureDebut, minuteDebut, "00", "00");
// I select the sheet to writing
var ss_calendrier = SpreadsheetApp.getActive().getSheetByName('Calendrier');
// I write my new date in my new sheet
ss_calendrier.getRange('B4').activate().setValue(dateheureDebut);
In debug I have:
dateDebut->Date (541813791)->Thu Apr 02 2020 03:00:00 GMT-0400 (EDT)
dateDebutSTR->String->"Thu Apr 02 2020 03:00:00 GMT-0400 (EDT)"
jourDebut->String->"02"
moisDebut->String->"3"
anneeDebut->String->"2020"
heureDebut->String->"09"
minuteDebut->String->"02"
dateheureDebut->Date (541917478)->Thu Apr 02 2020 09:02:00 GMT-0400 (EDT)
And in true, in the second file I have:
01/06/2020 06:02
The hour et the format is not good.

Try this:
function whoknowswhat() {
var mA=['jan','feb','mar','apl','may','jun','jul','aug','sep','oct','nov','dec'];
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Evenement');
var dt=sh.getRange('E21').getValue().trim();
var year=dt.slice(6);
var month=mA.indexOf(dt.slice(2,5));
var day=parseInt(dt.slice(0,2));
var hour=sh.getRange('G21').getValue().trim();
var minute=sh.getRange('I21').getValue().trim();
var dateheureDebut=new Date(year,month,day,hour,minute, 0);
var ss_calendrier=SpreadsheetApp.getActive().getSheetByName('Calendrier');
ss_calendrier.getRange('B4')setValue(dateheureDebut);
}

You can use the method getDisplayValue() to obtain the value that is displayed in the Sheet. Afterwards, it is easier to parse it and generate the final string from its data. You can see an example using this technique below:
function copyDate() {
var evenementSheet = SpreadsheetApp.getActive().getSheetByName('Evenement');
var months = ["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"];
var dateValues = evenementSheet.getRange('B7').getDisplayValue().split(' ');
var anne = dateValues[2];
var jour = dateValues[0];
var mois = months.indexOf(dateValues[1])+1;
var heure = evenementSheet.getRange('G21').getDisplayValue();
var minute = evenementSheet.getRange('I21').getDisplayValue();
var result = Utilities.formatString('%s-%s-%s %s:%s',
anne,
mois.length > 1 ? mois : '0' + mois,
jour.length > 1 ? jour : '0' + jour,
heure,
minute);
var calendrierSheet = SpreadsheetApp.getActive().getSheetByName('Calendrier');
calendrierSheet.getRange('B4').setValue(result);
}

Related

Script calls newDate and adds 5 days. I am looking to format the output to just date

Script for current date + 5 sends an email with exact 5 days from now. I want this to only output the date leaving out the timestamp
current output is: Sun Jul 10 2022 09:29:16 GMT-0400 (Eastern
Daylight Time)
expected output is: 07/0/2022
Here is what I have tried.
function findEmailAddress() {
var ss = SpreadsheetApp.getActive();
var sh1 = ss.getSheetByName('Working');
var vs1 = sh1.getRange('H1:H' + sh1.getLastRow()).getValues().flat();
var sh2 = ss.getSheetByName('Match');
var vs2 = sh2.getRange('A2:B' + sh2.getLastRow()).getValues();
var matchRows = vs2.filter(row => row[0].length && vs1.includes(row[0]));
matchRows.forEach(row => {
var mailMatch = row[1];
var curDate = new Date();
var date5 = curDate.setDate(curDate.getDate() + 5);
var dateFormat = moment(date5).format('DD/MM/YY');
var sub = "Action Required!!! 5 Days Til Expiration"
var bod = 'You have a new expiration date for completion'
+ dateFormat + ' all tasks associated with this must be complete. *This email is automatically generated do not reply*'
GmailApp.sendEmail(mailMatch, sub, bod);
});
}
I am stumped as to why this doesn't work.
Try it this way:
function findEmailAddress() {
var ss = SpreadsheetApp.getActive();
var sh1 = ss.getSheetByName('Working');
var vs1 = sh1.getRange('H1:H' + sh1.getLastRow()).getValues().flat();
var sh2 = ss.getSheetByName('Match');
var vs2 = sh2.getRange('A2:B' + sh2.getLastRow()).getValues();
var matchRows = vs2.filter(row => row[0].length && vs1.includes(row[0]));
matchRows.forEach(row => {
var mailMatch = row[1];
var curDate = new Date();
curDate.setDate(curDate.getDate() + 5);
let d = Utilities.formatDate(curDate,Session.getScriptTimeZone(),"MM/dd/yyyy")
var sub = "Action Required!!! 5 Days Til Expiration"
var bod = 'You have a new expiration date for completion'
+ d + ' all tasks associated with this must be complete. *This email is automatically generated do not reply*'
GmailApp.sendEmail(mailMatch, sub, bod);
});
}

How to check if date in a cell + 5 = today? (Google Apps Script + Google Sheets)

I'm trying to get a date from a cell, add 5 days to it, and check if that date is today. Here's what I've tried:
function test() {
sheet = SpreadsheetApp.getActive();
var today = new Date(new Date().setHours(0,0,0,0));
var weekStartDate = sheet.getRange('B5').getValue().getTime();
var newDate1 = new Date(new Date().setHours(0,0,0,0));
var newDate5 = new Date(new Date().setHours(0,0,0,0));
newDate1.setTime(weekStartDate + (1*24*60*60*1000));
newDate5.setTime(weekStartDate + (5*24*60*60*1000));
if(newDate5==today){
var answer = 'Yes';
} else{
var answer = 'No';
}
Logger.log(today);
Logger.log(newDate1);
Logger.log(newDate5);
Logger.log(answer);
}
The log shows:
11:29:59 AM Info Wed Jul 21 00:00:00 GMT-04:00 2021
11:29:59 AM Info Sat Jul 17 00:00:00 GMT-04:00 2021
11:29:59 AM Info Wed Jul 21 00:00:00 GMT-04:00 2021
11:29:59 AM Info No
How do I get "answer" to return "Yes"?
Screenshot
To compare two dates, we use values of these dates. This means if you changed newDate5 == today with newDate5.valueOf() == today.valueOf() it will return Yes.
Here is a simplified version of your code:
function test() {
var sheet = SpreadsheetApp.getActive();
var today = new Date().setHours(0,0,0,0).valueOf();
var dateToCompare= new Date(sheet.getRange('B5').getValue()).valueOf();
var dayInMs = 24*60*60*1000
Logger.log(today);
Logger.log(dateToCompare);
Logger.log(today == dateToCompare + 5*dayInMs);
}
Just in case
function myFunction() {
// date from cell 'A1'
var date = SpreadsheetApp.getActiveSheet().getRange('A1').getValue();
// today
var today = new Date();
// function to add 5 days to a date
const five_days_later = (d) => new Date(d.setDate(d.getDate() + 5));
// function to compare two dates
const if_same_date = (d1, d2) => d1.getDate() == d2.getDate() &&
d1.getMonth() == d2.getMonth() && d1.getYear() == d2.getYear();
// test
Logger.log(if_same_date(five_days_later(date), today));
}
var now = new Date();
var then = new Date("2021-07-16");
const to_str = x => '' + x.getYear() + x.getMonth() + x.getDate();
const if_same_date = (d1, d2) => to_str(d1) == to_str(d2);
const plus_days = (date, gap) => new Date(date.valueOf() + gap*24*60*60*1000);
console.log(if_same_date(now, plus_days(then, 5)));

Find and match a date in array

I'm trying to make a function in order to find & match the date of day in a array.
But for a weird reason, if two dates are matching, my function never find the match.
So..., if I change my date by an other string (ex : "foo" match with "foo"), it's work.
Here my code, and then the log return. Have you an idea why my script can't match two equal dates ?
Thank you !
function hideBeforeToday(values, value)
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.setActiveSheet(ss.getSheetByName(roadmapSS))
var range = sheet.getRange(4, 11, 1, sheet.getLastColumn())
var values = range.getValues();
Logger.log(values);
var value = moment().set({hour:0,minute:0,second:0,millisecond:0}).utc().toDate();
Logger.log("date", value);
for(var i = 0; i < values.length; i++) {
if(values[i].indexOf(value) > -1) {
Logger.log("data found");
}
}
}
[18-01-11 13:49:33:065 CET] Logger.log([arrayValues, [[[Wed Jan 10 00:00:00 GMT+01:00 2018, Thu Jan 11 00:00:00 GMT+01:00 2018]]]]) [0 secondes]
[18-01-11 13:49:33:067 CET] Logger.log([dateOfDay, [Thu Jan 11 00:00:00 GMT+01:00 2018]]) [0 secondes]
[18-01-11 13:49:33:070 CET] Script exécuté [durée totale d'exécution : 0,535 secondes]
Look at this example:
var date1 = new Date("Thu Jan 11 00:00:00 GMT+01:00 2018");
var dates = [date1];
console.log(date1); // prints 2018-01-10T23:00:00.000Z
console.log(dates.indexOf(date1)); // prints 0
While this:
var date1 = new Date("Thu Jan 11 00:00:00 GMT+01:00 2018");
var dates = [new Date("Thu Jan 11 00:00:00 GMT+01:00 2018")];
console.log(date1); // prints 2018-01-10T23:00:00.000Z
console.log(dates.indexOf(date1)); // prints -1
I don't know what data you have in the spreadsheet, if it is a string or a Date object, but try converting both to the same type before comparing. Check their types and perhaps use the toISOString() function?

Google Apps Script: comparing dates

I'm having a weird issue comparing dates in my Google Apps Script.
For this, my sheet has a date in cell.getValue() so on the
e.range.setNote(cell.getValue() + " --- " + startDate);
line, the note shows two dates that appear identical, but they aren't because the following if statement is not satisfied. Am I missing something here with the comparisons? Thanks.
function onEdit(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sss = ss.getSheetByName("Sheet1");
var row = e.range.getRow();
var startDate = sss.getRange(row, 3).getValue(); //Wed Aug 10 2016 00:00:00 GMT-0600 (GALT)
var cell = ss.getSheetByName("Sheet2").getRange(1, 1);
e.range.setNote(cell.getValue() + " --- " + startDate); //Wed Aug 10 2016 00:00:00 GMT-0600 (GALT) --- Wed Aug 10 2016 00:00:00 GMT-0600 (GALT)
if (cell.getValue() === startDate){
cell.setBackground('blue');
}
}
I think you need to compare as dates https://stackoverflow.com/a/493018/1393023
Replace
cell.getValue() === startDate
to
cell.getValue().getTime && startDate.getTime && cell.getValue().getTime() === startDate.getTime()

Values Match if not being met :S

function unupdatedRows () {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var formSheet = ss.getSheets()[0];
var numRows = formSheet.getLastRow();
var lastRow = formSheet.getRange(numRows,1);
var lastDate = lastRow.getValue();
Logger.log(lastUpdate());
Logger.log(lastDate);
if (lastDate == lastUpdate()){
Logger.log("MATCH! Sheet is up to date");
}
};
Logger output:
[14-06-24 16:12:53:188 EDT] Mon Jun 23 01:50:10 GMT-04:00 2014
[14-06-24 16:12:53:188 EDT] Mon Jun 23 01:50:10 GMT-04:00 2014
I should be seeing "MATCH! Sheet is up to date" in the logger too. Why isn't the if statement being met?
Avoid checking equality on date objects, they will never be equal (you can use > and < comparison though), do it on their string representation for instance or from any derived value (year, month, day, hours...) or even on their native values (millisec).