datetime switching timezone from google app script to google sheets intentionally - google-apps-script

I'm trying to fill some google sheets cells with the current date and time, date is ok, but the time is off by 6 hours.
This is the code I used:
function start() {
var ss = SpreadsheetApp.getActive();
var timestamp = new Date();
Logger.log('start, timestamp: ' + timestamp);
var date = Utilities.formatDate(timestamp, 'Europe/Brussels', "dd/MM/yyyy");
Logger.log('date: ' + date);
var time = Utilities.formatDate(timestamp, 'Europe/Brussels', "HH:mm:ss");
Logger.log('time: ' + time);
var sheet = SpreadsheetApp.getActive().getSheetByName(SheetName);
sheet.appendRow([date,time]);
}
The logs of the date and time do give me the expected date and time, but once the appendRow is done, in Google Sheets, I'm getting the offset time...
I have tried to offset it myself, to correct to the right value, but that didn't change anything.

That is odd, I tested your code and it works for me.
It's properly showing the timezone of 'Europe/Brussels'. Also, tested using var time = Utilities.formatDate(timestamp, 'GMT+1', "HH:mm:ss"); and both display the correct time inside the Execution log and the cell.
If you test the code in a new Apps Script does it show the incorrect time zone too? Have you reviewed the time timezone inside Project Settings > General Settings?
If after all that you still have the same issue, I will recommend creating an issue tracker by following the steps here.

Related

Script places the dates correctly on my goog cal, then misplaces them all one day early, then places the last one correctly again

The script places the dates correctly on my Google Calendar, then misplaces them all one day early, then places the last one correctly again.
input from google sheet, displayed in Google Calendar
1/4/23 -> 1/4/23 put in goog cal correctly
1/8/23 -> 1/7/23 - one day off
2/5/23 -> 2/4/23 - one day off
6/18/23 -> 6/17/23 - one day off
10/15/23 -> 10/15/23 - correct
function addEvents(){
var ss =
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lr = ss.getLastRow();
var cal =
CalendarApp.getCalendarById("#group.calendar.google.com");
var data = ss.getRange("A1:C" + lr).getValues();
for(var i = 0; i<data.length;i++){
cal.createAllDayEvent(data[i][0], new Date(data[i][1]),
{description:'PRO: ' + data[i][2]});
}
}
three columns in the google sheet
title, date, and description
Try GetDisplayValues()
var data = ss.getRange("A1:C" + lr).GetDisplayValues();
and potentially format the column as yyyy-MM-dd.
This will ensure the data the script is using is the same as you see on the sheet. Formatting the column will ensure new Date() converts the the data correctly.
If its still off add a couple hours to your Date object to ensure the time is firmly in the middle of the day.
let today = new Date();
today.setHours(today.getHours() + 4);

Google Scripts Format Date Creates Impossible Date

In a very stripped down sense, this is my issue. I am creating a script that will look for a folder with a given name inside a particular folder. If the script finds a folder with that name, it will move the current document to that folder. If not, it should create a folder with that name, and then move the document.
The current naming convention on folders is "Billed 6/18", as an example.
Right now my script is throwing the date out in a weird way, and that won't help me with my later search by file name in a string format.
function MoveTicket() {
var ss = SpreadsheetApp.getActive()
var billfold = DriveApp.getFolderById(id)
var currentdate = Utilities.formatDate(new Date(), "GMT-4", "M/D")
var billfoldname = ('Billed ' + currentdate)
Logger.log(billfoldname)
}
But my log shows [20-06-18 15:41:59:480 EDT] Billed 6/170
I've attempted changing the timezone from GMT-4 to UTC, or changing the date format to M/DD or MM/DD, and I still see the same issue. Just logging new Date() does show the correct date.
Where is it getting 170 for the date? How can I correct it?
Solved. Was using D which gave day of the year instead of d which gave day of the month.
var currentdate = Utilities.formatDate(new Date(), "GMT-4", "M/d")
Simple Date Format

Is there a way to insert yesterday's date statically in a cell using a macro in google sheets?

I have a macro to run at the beginning of every day which inserts today's date, grabs the previous day's data inputs, pastes them below today's date, and then formats it all. The issue is that I need it to display yesterday's date, not today's, and I need it to remain that date over time.
I've searched all over for solutions to this issue, but I can't find anything that answers my issue. Maybe I'm just bad at searching. This is what the code in question currently is:
function MorningRoutine() {
var spreadsheet = SpreadsheetApp.getActive();
var date = new Date();
spreadsheet.getActiveRangeList().setValue(date);
I need the macro to input yesterday's date, but this currently displays today's.
This will give yesterday date:
function MorningRoutine() {
var spreadsheet = SpreadsheetApp.getActive();
var date = new Date();
date.setDate(d.getDate()-1);
spreadsheet.getActiveRangeList().setValue(date);
}

How do I add "CST" time zone in the timestamp in the Google sheets code below? Also, will it know Daylight savings time?

Everything works on this code for me except for when the timestamp happens it's 2 hours behind my actual time. How do I get it to know CST time zone or is it something within Google Sheets that needs to be changed? This is my first time using code and I'm surprised I've gotten this far.
function onEdit(e) {
var sh = e.source.getActiveSheet();
var sheets = ['TK Assignments']; // Which sheets to run the code.
// Columns with the data to be tracked. 1 = A, 2 = B...
var ind = [15, 17, 19].indexOf(e.range.columnStart);
// Which columns to have the timestamp, related to the data cells.
// Data in 1 (A) will have the timestamp in 4 (D)
var stampCols = [16, 18, 20]
if(sheets.indexOf(sh.getName()) == -1 || ind == -1) return;
// Insert/Update the timestamp.
var timestampCell = sh.getRange(e.range.rowStart, stampCols[ind]);
timestampCell.setValue(typeof e.value == 'object' ? null : new Date());
The Apps Script file and the spreadsheet file, both have their own timezone setting. The default time zone settings in the script and Sheet files is the time zone in your browser. When a date is created in the code, it's created by default with the script's time zone, not the Sheets timezone.
You can:
1. Modify the script timezone
Within the script editor, go to File>Project Properties. In the Info tab, scroll down near the bottom and select the "Time zone" setting as you wish. Since those are "Time zones" (and not offsets) they will consider DST. If you want, you can read more about this here.
2. Use the Spreadsheet's settings Timezone
The Spreadsheet also has a timezone setting in Files>Spreadsheet Settings.
Within the script. you can use Utilities.formatDate( new Date(), Session.getScriptTimeZone() , "MM/dd/yy HH:mm"). The getScriptTimeZone() function will get the timezone settings found in Files/Project properties.
If, for some reason, you prefer to use a Timezone different than the one set in your Script settings or your Sheet settings, you can set whichever you prefer upon calling Utilities.formatDate(). You can see more information here: https://developers.google.com/apps-script/reference/utilities/utilities#formatdatedate,-timezone,-format

How to get the current time in Google spreadsheet using script editor?

There is an option to write a script and bind it to a trigger. The question is, how to get the current time in the script body?
function myFunction() {
var currentTime = // <<???
}
use the JavaScript Date() object. There are a number of ways to get the time, date, timestamps, etc from the object. (Reference)
function myFunction() {
var d = new Date();
var timeStamp = d.getTime(); // Number of ms since Jan 1, 1970
// OR:
var currentTime = d.toLocaleTimeString(); // "12:35 PM", for instance
}
I considered with timezone in my Google Docs like this:
timezone = "GMT+" + new Date().getTimezoneOffset()/60
var date = Utilities.formatDate(new Date(), timezone, "yyyy-MM-dd HH:mm"); // "yyyy-MM-dd'T'HH:mm:ss'Z'"
my script for Google docs
Use the Date object provided by javascript. It's not unique or special to Google's scripting environment.
Anyone who says that getting the current time in Google Sheets is not unique to Google's scripting environment obviously has never used Google Apps Script.
That being said, do you want to return current time as to what? The script user's timezone? The script owner's timezone?
The script timezone is set in the Script Editor, by the script owner. But different authorized users of the script can set timezone for the spreadsheet they are using from File/Spreadsheet settings menu of Google Sheets.
I guess you want the first option. You can use the built in function to get the spreadsheet timezone, and then use the Utilities class to format date.
var timezone = SpreadsheetApp.getActive().getSpreadsheetTimeZone();
var date = Utilities.formatDate(new Date(), SpreadsheetApp.getActive().getSpreadsheetTimeZone(), "EEE, d MMM yyyy HH:mm")
Alternatively, get the timezone offset from UTC time using Javascript's date method, format the timezone, and pass it into Utilities.formatDate().
This requires one minor adjustment though. The offset returned by getTimezoneOffset() runs contradictory to how we often think of timezone. If the offset is positive, the local timezone is behind UTC, like US timezones. If the offset is negative, the local timezone is ahead UTC, like Asia/Bangkok, Australian Eastern Standard Time etc.
const now = new Date();
// getTimezoneOffset returns the offset in minutes, so we have to divide it by 60 to get the hour offset.
const offset = now.getTimezoneOffset() / 60
// Change the sign of the offset and format it
const timeZone = "GMT+" + offset * (-1)
Logger.log(Utilities.formatDate(now, timeZone, 'EEE, d MMM yyyy HH:mm');
The Date object is used to work with dates and times.
Date objects are created with new Date().
var date= new Date();
function myFunction() {
var currentTime = new Date();
Logger.log(currentTime);
}