google app script how to get date in string date(spread sheet) - google-apps-script

I want to compare the date that was created in the spreadsheet with a specific date.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var spreaddate = ss.getSheetByName("sheet123").getRange("B2").getValue();
//--> Thu Dec 12 00:00:00 GMT+09:00 2019
var comparedate = new date(yyyy-mm-dd)//somting like this
if(spreaddate > comparedate){
do something
}
The spreaddate is not recognized as a date.
Even if I try to convert it to a date, it's hard because it's written in letters, not numbers like Thu Dec.
What should I do?

I think the problem is that you're not correctly defining your comparedate. You need to use a capital 'D' new Date().

Related

How do I split text (from Sheets) in Google Apps Script (in Slides)?

I am accessing data from Google Sheets and putting it onto Google Slides. The data I'm using has dates in the format "Thu Jan 30 00:00:00 GMT-08:00 2020". I want to split it such that I only have "Thu Jan 30".
My code so far is:
var data = sheet.getDataRange().getValues();
for (var i = 0; i < data.length; i++) {
var date = data[i][0];
var splitDate = date.split("00:00");
Logger.log(splitDate[0]);
Logger.log(data[i][1]);
}
However, I get an error that says "TypeError: date.split is not a function". Is there another function I can use to split the date?
In your situation, when getValues() is used, Thu Jan 30 00:00:00 GMT-08:00 2020 is retrieved. And you want to retrieve Thu Jan 30.
When Thu Jan 30 is putting to the cell in the Spreadsheet, I think that getDisplayValues() might be suitable instead of getValues().
Reference:
getDisplayValues()

How to format Date in Google Script

I am trying to write a small Google Script which takes data from some cells of Google Sheet and Paste it in the GMAIL.
However, while pasting the 'Date Values' it always displays it in the following manner:-
Mon Apr 15 2019 00:00:00 GMT+0530 (IST)
Fri Apr 26 2019 00:00:00 GMT+0530 (IST)
But I need the dates in an appropriate way i.e.
"Mon Apr 15 2019" or
"Fri 04/26/2019"
I gone through these possible options i.e. Utilities.formatDate & .Split but somehow I am not able to write these codes appropriately. Can you please help me with this matter. Below I have mentioned the entire issue in detail.
My Code
function temp2() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var dataSheet = ss.getSheetByName('Sheet1');
var templateSheet = ss.getSheetByName('Sheet2');
var emailTemplate2 = templateSheet.getRange("G1").getValue();
var rec = templateSheet.getRange("C1").getValue();
var sub = templateSheet.getRange("D1").getValue();
var date = templateSheet.getRange("E1").getValue();
// Logger.log(rec);
MailApp.sendEmail(rec, sub, emailTemplate2);
}
here var date = templateSheet.getRange("E1").getValue(); is the part of code which picks value of date.
Do let me know if you need more details in this regard
Regards,
Alok
Requirement:
Format date value from cell in Google Apps Script.
Solution:
Pass value to date constructor new Date() then format using Utilities.formatDate().
// pass date to date constructor
var date = new Date(templateSheet.getRange("E1").getValue());
// "Mon Apr 15 2019" example
var formattedDate = Utilities.formatDate(date, "GMT+0", 'E MMM dd yyyy');
// "Fri 04/26/2019" example
var formattedDate = Utilities.formatDate(date, "GMT+0", 'E MM/dd/yyyy');
Note: I've set this to timezone "GMT+0" by default, you can change this to whichever time zone you need.
References:
new Date() for date constructor.
Utilities.formatDate() for formatting dates in Google Apps Script.
SimpleDateFormat for date format strings.

How to get google sheet's cell values as is using google script

I'm about to use google sheet as my database for my android app small project. I'm using Google Script to handle the request from my app.
In my google sheet, I store;
A2:A = date as dd/mm/yyyy e.g 21/12/2019 but
the display format is dd-MMM e.g 21-Dec
C2:D = time as hh:mm:ss e.g 21:00:00 but
the display format is hh:mm e.g 21:00
Yes, I need a different format for the display and input.
My google sheet:
When I use google script to get a value of the cell, it seems that it is reformatted
the date looks like this: Sat Jan 01 2019 00:00:00 GMT+0700 (ICT)
the time the other hand, change in value a bit. 20:00:00 to 19:52:48
Is there any function to get cell real values as text without being reformatted?
The only thing that I can think of is instead of using getValues(), I can use getDisplayValues(). The values will not be reformatted, but it is not a solution for me, as it will take the display format.
Snippet of my code:
function updateData(e, sheet) {
var tgl = e.parameter.tgl;
var dtg = e.parameter.dtg;
var plg = e.parameter.plg;
var lbr = e.parameter.lbr;
var rangeHead = sheet.getRange("A2:A");
var valuesHead = rangeHead.getValues();
var rangeFirst = sheet.getRange("C2:D")
var valuesFirst = rangeFirst.getValues();
var rangeSecond = sheet.getRange("G2:G")
var valuesSecond = rangeSecond.getValues();
for (var i = 0; i < valuesHead.length; i++) {
if (valuesHead[i][0] === tgl) {
if(dtg!="null") { valuesFirst[i][0] = dtg; }
if(plg!="null") { valuesFirst[i][1] = plg; }
if(lbr!="null") { valuesSecond[i][0] = lbr; }
break;
}
}
rangeFirst.setValues(valuesFirst);
rangeSecond.setValues(valuesSecond);
}
The code won't work as I will comparing 21/12/2019 with Sat Jan 01 2019 00:00:00 GMT+0700 (GMT).
[UPDATE 1]:
Thank you P-Burke for the enlightenment. Now, I have an idea to solve the date problem. I know that the script pulls the date as date object, but I am unaware that it also saves as a date object. (hehe my bad) I don't realize it as there is no autocomplete when I call values[0][0]. of course, as it recognizes the object type at the run time.
So, my workaround will be; I will call getDate, getMonth+1, and getYear. After that, I will compare with my parameter freely.
Though, the time cell still a bit confusing for me. the time offset is 18 minutes 12 seconds. I don't think it's because of timezone different and my computer clock. the timezone different is too big and I 've made sure that the script, spreadsheet, and local timezone all the same. My computer clock is also only a minute less behind.
[UPDATE 2]:
Alright, enough with the confusion. It seemed that the script converts the time to Date object respect to my local timezone. I got this answer from another thread. So, actually, my local timezone changes many times and some of them have offset smaller than hours unit (one of the timezones used in my area is UTC +7:07:12h). The only source documenting those changes I could find is from https://www.timeanddate.com/time/zone/indonesia/jakarta. Finally, I gave up. For my goodness sake, I will just use getDisplayValue and ignore the seconds. Unless you guys have any other workaround, I will be so grateful.
Thank you once again to the community.
Firstly, and I don't know if this is related to your issue, but the spreadsheet and the script each have their own timezone setting:
Spreadsheet: File >> Spreadsheet Settings >> Time Zone.
Script: File >> Project Properties >> Time Zone.
And if these are different that can lead to confusion. One answer, if all your users are in the same timezone, is to set them to the same. Alternatively these can be determined from within your script as described here, and logic included to handle any differences. I don't understand the few minutes time difference, perhaps your PC clock is inaccurate?
The other point, which I think is more relevant to your question is that you effectively have multiple date/time formats in play. The picture below shows that in the spreadsheet times are edited in one format (02/01/2019 09:00:00), but displayed in whatever format is defined for the cell using the format menu. Yet when the cell values are pulled into a script using getValues() and displayed they appear as follows: Values: [[Thu Jan 31 09:00:00 GMT+00:00 2019, Wed Jan 02 09:00:00 GMT+00:00 2019]].
Yet in the code below, values[0][0] and values[0][1] are actually JavaScript Date() objects and can be compared in the usual way, alternatively they can be reformatted into whatever string format you require as illustrated in the code below:
function myFunction() {
var ss = SpreadsheetApp.getActive();
var ws = ss.getActiveSheet();
var input_range = ws.getRange("A1:B1");
var values = [];
values = input_range.getValues(); // Returns a multi-dimensional array, hence [0][0] to access.
Logger.log("Values: %s", values);
// As Date() objects the usual methods are available.
Logger.log("Date().getMonth(): %s",values[0][0].getMonth());
Logger.log("Date().getYear(): %s",values[0][1].getYear());
// This formats the date as Greenwich Mean Time in the format
// year-month-dateThour-minute-second.
var formattedDate = Utilities.formatDate(values[0][0], "GMT", "yyyy-MM-dd'T'HH:mm:ss'Z'");
Logger.log(formattedDate);
formattedDate = Utilities.formatDate(values[0][1], "GMT", "yyyy-MM-dd'T'HH:mm:ss'Z'");
Logger.log(formattedDate);
}
Logger.log output:
[19-01-31 11:43:17:635 GMT] Values: [[Thu Jan 31 09:00:00 GMT+00:00 2019, Wed Jan 02 09:00:00 GMT+00:00 2019]]
[19-01-31 11:43:17:636 GMT] Date().getMonth(): 0.0
[19-01-31 11:43:17:637 GMT] Date().getYear(): 2019.0
[19-01-31 11:43:17:638 GMT] 2019-01-31T09:00:00Z
[19-01-31 11:43:17:638 GMT] 2019-01-02T09:00:00Z

Getting day of the week not working when using setNumberFormat

I would like programably enter the date into a cell and format it to include the Day of the week (Mon, Tue, Wed,...). If I use the .setNumberFormat method (which I would prefer to do because it keeps the info as a date), the simpleDateFormat for Day of the week does not work. If I use Utilities.formatDate I can use 'EEE, MM/dd' and it will show up correctly, but I lose the date format.
function setformat(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var lab = ss.getSheetByName("test2");
// This is what I want to use but the day of the week 'EEE' doesn't work
var todaySNF = new Date();
lab.getRange("a1").setValue(todaySNF);
lab.getRange("a1").setNumberFormat('EEE, MM/dd'); // Should read Wed, 09/23 but reads EEE, 09/23 instead.
var cellA1asDate = new Date(lab.getRange("a1").getValue());
Logger.log(cellA1asDate);}
use this instead :
lab.getRange("a1").setNumberFormat('DDD, MM/dd');

Trying to subtract 5 days from a defined date - Google App Script

I'm trying to write a script which is supposed to send out an email and create two calender entries when submitting a form. To be honest, this is my first script and I am very happy that the email is send out and the calender entries are working as well. The thing which gives me a headache is to subtract 5 days (actually x days) from a defined date.
First I thought I could simply do something like
var liveday = e.values[2];
var newday = liveday-5;
well, this didn't work :-)
I tried more:
var newtime = new Date(liveday);
var yr = newtime.getYear();
var dt = newtime.getDay();
var mt = newtime.getMonth();
var dtnew = dtnew.setDate(mt, dt-5, yr);
But here I received 1418256000000 whereas liveday = 12/01/2014. Not sure why days were added, rather than subtracted.
I am quite confused here and the answer can't be that hard.
I just want to subtract 5 days from 12/01/2014 to receive 11/27/2014.
Thanks for having a look
the comment sends you to a rather complicated serie of codes... there is a far more simple way to get that, here is the code :
function test() {
Logger.log('today= '+new Date()+' and 5 days ago is '+subDaysFromDate(new Date(),5));
}
function subDaysFromDate(date,d){
// d = number of day ro substract and date = start date
var result = new Date(date.getTime()-d*(24*3600*1000));
return result
}
Logger result :
[13-11-18 23:39:50:364 CET] today= Mon Nov 18 2013 23:39:50 GMT+0100 (CET) and 5 days ago is Wed Nov 13 2013 23:39:50 GMT+0100 (CET)
if you want to get the date in the form dd/mm/yyyy use Utilities.formatDate(date, timeZone, 'dd/MM/yyyy), see doc here