Timezone conversion in a Google spreadsheet - google-apps-script

I know this looks simple.
In a Google spreadsheet, I have a column where I enter time in one timezone (GMT)
And another column should automatically get time in another time zone(Pacific Time)
GMT | PT
----------|------------
5:00 AM | 9:00 PM
As of now I am using
=$C$3-time(8,0,0)
The problem here is, I want to change the time formula for Daylight savings.
Is there any function or script available which can take the daylight saving into calculation automatically.

Short answer
There is no built-in function but you could build a custom function.
Example
/**
* Converts a datetime string to a datetime string in a targe timezone.
*
*#param {"October 29, 2016 1:00 PM CDT"} datetimeString Date, time and timezone.
*#param {"Timezone"} timeZone Target timezone
*#param {"YYYY-MM-dd hh:mm a z"} Datetime format
*#customfunction
*/
function formatDate(datetimeString,timeZone,format) {
var moment = new Date(datetimeString);
if(moment instanceof Date && !isNaN(moment)){
return Utilities.formatDate(moment, timeZone, format)
} else {
throw 'datetimeString can not be parsed as a JavaScript Date object'
}
}
NOTE:
new Date(string) / Date.parse(string) implementation in Google Apps Script doesn't support some timezones abbreviations.
From https://tc39.es/ecma262/#sec-date-time-string-format
There exists no international standard that specifies abbreviations for civil time zones like CET, EST, etc. and sometimes the same abbreviation is even used for two very different time zones.
Related
Get UTC offset from timezone abbreviations
Explanation
In order to consider daylight saving time zones the input argument for of the value to be converted should include the date, no only the time of the day. You could set a default date and time zone to build the datetimeString by concatenating it before calling the formula.
=formatDate("October 29, 2016 "&A2&" GMT","PDT","hh:mm a")
For the target timezone besides the three letter abbreviation we could use TZ database names like America/Los_Angeles, example:
=formatDate("October 29, 2016 "&A2&" GMT","America/Los_Angeles","HH:mm")
If timezone abbreviation and TZ name fails for the datetimeString use time offsets (i.e. UTC-4).
See also
Calculating year, month, days between dates in google apps script
References
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date

This tutorial was amazingly helpful: https://davidkeen.com/blog/2017/01/time-zone-conversion-in-google-sheets/
Google Sheets does not have a built in way of converting time zone data but by using the power of Moment.js and Google’s script editor we can add time zone functionality to any sheet.
These are the files I copied into my script project:
https://momentjs.com/downloads/moment-with-locales.js saved as moment.js
https://momentjs.com/downloads/moment-timezone-with-data.js saved as moment-timezone.js
Make sure you add the moment.js script first and have it above the moment-timezone.js script because moment-timezone.js depends on it.
Then in your other script project, your Code.gs file can look like this:
var DT_FORMAT = 'YYYY-MM-DD HH:mm:ss';
/**
https://stackoverflow.com/questions/34946815/timezone-conversion-in-a-google-spreadsheet/40324587
*/
function toUtc(dateTime, timeZone) {
var from = m.moment.tz(dateTime, DT_FORMAT, timeZone);//https://momentjs.com/timezone/docs/#/using-timezones/parsing-in-zone/
return from.utc().format(DT_FORMAT);
}
/**
https://stackoverflow.com/questions/34946815/timezone-conversion-in-a-google-spreadsheet/40324587
*/
function fromUtc(dateTime, timeZone) {
var from = m.moment.utc(dateTime, DT_FORMAT);//https://momentjs.com/timezone/docs/#/using-timezones/parsing-in-zone/
return from.tz(timeZone).format(DT_FORMAT);
}

The easiest method is using a simple calculation.
Use =NOW() command in sheets and subtract it with the time difference divided by 24.
Example:
IST to Colombia
=NOW()-(10.5/24)
The time difference from India to Colombia is 10hours and 50min, we need to subtract it from the "Now" time and divide it by 24.
If the time zone is ahead of your place, then you need to add it.
Example:
IST to JAPAN:
=NOW()+(3.5/24)
=Now is set to US time by default, you can change it under general in settings.
enter image description here
enter image description here

I had the same problem (convert Manila Time to Sydney Time and automatically adjust for daylight saving time) when I found this page.
I didn't want to have a custom function but I found that, in Sydney, AEST (Australian Eastern Standard Time) starts on the first Sunday of April and AEDT (Australian Eastern Daylight Time) starts on the first Sunday of October.
So I thought, if I could find a formula that detects whether a date falls between the first Sunday of April and first Sunday of October (Standard Time) then I can automatically add 1 hour to the usual 2 hours to Manila time during Daylight Saving Time (dates falling outside the two dates) to have Sydney Time.
These two Excel solutions worked fine in Google Sheets:
How You Can Determine the First Sunday in a Month in Excel
How to determine if a date falls between two dates or on weekend in Excel
First Sunday of April this year (A1):
=CONCATENATE("4/1/",Year(today()))+CHOOSE(WEEKDAY(CONCATENATE("4/1/",Year(today())),1),7,6,5,4,3,2,1)
First Sunday of October this year (A2):
=CONCATENATE("10/1/",year(today()))+CHOOSE(WEEKDAY(CONCATENATE("10/1/",year(today())),1),7,6,5,4,3,2,1)
DST detector (A3) — if a date falls outside these two dates, it's DST in Sydney:
=IF(AND(today()>A1,today()<A2),"AEST","AEDT")
Time in Sydney (A4):
=NOW()+TIME(IF(A3="AEDT",3,2),0,0)
NOW() can be changed to any time format for tabulation:

I'm a new contributor and a novice, but I stumbled upon a function that had not been mentioned despite many hours of searching on the Sheets/Time Zone issue. Hoping this relatively simple solution will help.
For my sheet, I just want to add a row and automatically populate the local sheet date and time in the first two cells.
The .getTimezoneOffset() returns the difference in minutes between the client TZ and GMT, which in NY during Daylight Savings Time is 240. The function returns a positive number for the zones with "GMT-x", and vice versa for zones with "GMT+x". Hence the need to divide by -60 to get the correct hour and sign.
function addRow() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
sheet.insertRows(2, 1);
rightNow = new Date();
var tzOffset = "GMT" + rightNow.getTimezoneOffset() / -60;
var fDate = Utilities.formatDate(rightNow, tzOffset, "MM-dd-yyyy");
var fTime = Utilities.formatDate(rightNow, tzOffset, "HH:mm");
sheet.getRange('A2').setValue(fDate);
sheet.getRange('B2').setValue(fTime);
sheet.getRange('C2').setValue(tzOffset);
}
I've since found that I'm not the first person to respond to the GMT correction connundrum mentioning .getTimezoneOffset(). However, this thread has the most views on this topic, so I figured this option deserves a mention.
DST ends here on November 7th, 2021, so I'll report back if it doesn't adjust as expected to "GMT-5"
.getTimezoneOffset()

That can also be done without macros. Just using functions and data manipulation will suffice. Explaning the whole process here would be a bit cumbersome. Just do your research on how the various time functions work and use your creativity.
Hint: Use =NOW() if you want both current date and time. You'll actually need that if you need to find out the precise diff in time between to different dates.
Use =NOW()-INT(NOW()) when you only want the time (with date truncated if both times fall on the same date). Then format the corresponding cell or cells for time (i.e. 4:30 PM), not for date-time (3/25/2019 17:00:00). The latter is the format you'd use when you want to show both date and time... like when you use NOW().
Also search online for the Daylight Saving Time offset for the various standard time zones (PT, MT, CT, ET, AT) with respect to the Coordinated Universal Time (UTC). For example, in 2019 the offset for Pacific Time is UTC-7 when DST is observed starting on March 10 at 2 AM (Pacific) until November 3 at 2 AM. That means that the difference in time from UTC to Pacific is 7 hours. During the rest of the year is 8 hours (UTC-8). During DST observance starting sometime in March (the 10th this yr) it goes from PST to PDT by moving clocks forward 1 hr, or what we know as UTC-7 (that's summer time). After DST observance it goes from PDT to PST by moving clocks back 1 hr again, or what we know as UTC-8 (or winter time). Remember that the clock is advanced one hour in March to make better use of time. That's what we call DST, or Daylight Saving Time. So after March 8 at 2 AM (this year in 2019) we are in UTC-7. In November, we do the opposite. In Nov 3 at 2 AM the clock is taken back one hour as the winter kicks in. At that point we are back in Standard Time. Seems a bit confusing but it's really not.
So, basically, for folks in PT they go from PST to PDT in March and from PDT to PST in November. The exact same process goes on with Mountain Time, Central Time and Eastern Time. But they have different UTC time offsets. MT is either UTC-6 or UTC-7. CT is either UTC-5 or UTC-6. And ET is either UTC-4 or UTC-5. All depending on whether we are in summer time when Daylight Saving is observed to make better use of daylight and working hours, or in winter time (AKA, Standard Time).
Study these thoroughly and understand how they work, and play around with the various time functions in Excel or Google Sheets like the TIME(#,#,#) and NOW() functions and such, and believe me, soon you'll be able to do about anything like a pro with plain functions without having to use VBA Google Apps Script. You can also use the TEXT() function, though, with tricks like =TEXT(L4,"DDD, MMM D")&" | "&TEXT(L4,"h:mm AM/PM"), where L4 contains you date-timestamp, to display time and date formats. The VALUE() function also comes in handy every now and then. You can even design a numerical countdown timer without the use of macros. You'd need to create a circular reference and set iterations to 1, and time display to say every 1 min, in your spreadsheet settings for that.
The official timeanddate dot com website is a good source of info for all to know about time zones and how daylight time is handled. They have all UTC offsets there too.

Create your own Timezone Converter in Google Sheets:
Step 1: Create your table for the timezone converter.
Step 2: Enter the times for your time zones in a column.
Note: Ensure that you select date/time format(Select Cell(s) -> Format -> Number -> Time/Date)
Step 3: Write a formula to convert timezone using the following functions
Google Sheet Functions
=HOUR(A8)+(B3*C3) converts the hours.
=MINUTE(A8)+(B3*C3) converts the minutes.
Step 4: Convert back to time format using TIME(h,m,s) function
=TIME(HOUR(A8)+(B3*C3), MINUTE(A8)+(B3*C3), SECOND(A8))
This is a simple way to convert timezones.
However, if you want to implement an accurate timezone converter that takes care of the previous day, next day, and beyond 24 hours, beyond 60 minutes, please use MOD operations and handle all the cases.
Visit(or Use) this google sheet for reference:
https://docs.google.com/spreadsheets/d/1tfz5AtU3pddb46PG93HFlzpE8zqy421N0MKxHBCSqpo/edit?usp=sharing

just use the TZData format to "pull" a sync from UTC and display your choice.
Example in order to "change" the display of your cell to Berlin local time
=fromUTC(N82, "Europe/Berlin")
or for Tokyo
=fromUTC(N82, "Asia/Tokyo")
or San Francisco
=fromUTC(N82, "America/Inuvik")
point of reference for Time Zones is here >>
https://en.wikipedia.org/wiki/List_of_tz_database_time_zones

Related

Google Forms createResponse with date decrements the day by 1

I am programmatically generating new form responses from rows of data in a Google Sheet (one approval workflow system generates new approval requests in a second approval workflow system). The data includes dates. My script takes the date value as a string from a cell, converts it into a native JavaScript date object, then submits this to a new form response using createResponse(). Here's the pertinent code:
var startDate = googleFormsDateStringToDate(eventDetails['Event Start Date']);
var r = item.createResponse(startDate);
For the most part, the system works robustly. Except for one intriguing problem - for any date after 29/04/2020, the date stored in the response is decremented by 1 day. Any date on or before this date works as expected, any date after is decremented by a day.
I have tried a few things.
The dates correspond to a start date and end date for an event. If the start date is before this date and the end date after, the end date will be decremented whilst the start date is recorded accurately. So I am certain the issue is directly related to whether the date I am submitting falls before or after this date.
I have tested extensively and am absolutely certain that the string-date conversion is working. If I retrieve the value of the response immediately after creating it (before the form response is even submitted), I find that it has been decremented:
var startDate = dateStringToDate(eventDetails['Event Start Date']);
Logger.log(startDate.toString()); // startDate is always accurate
var r = item.createResponse(startDate);
Logger.log(r.getResponse()); // if after 29/04/2020, will be decremented by 1 day
This tells me the issue is occurring precisely when I create the response and that it is occurring "at Google's end".
One of my suspicions is that it may be a timezone issue, but that would not explain why the issue is linked directly to this specific date. My other suspicion is that it may be to do with the fact that 2020 is a leap year, so we get 29/02/2020, and the date after which the error occurs is 29/03/2020. Perhaps somewhere behind Google's implementation of createResponse it is failing to account for the leap year?
Until I can identify the error, I plan to implement a workaround in which I will use getResponse() to check if the response date matches the intended date and correct accordingly. But I would prefer to understand what is causing the error (so I know if it is a bug requiring reporting, or simply my lack of understanding) and, if possible, find a solution.
So, specific questions: What is the source of the error? Is there a solution (rather than a workaround)?
EDIT
Whilst figuring out a workaround, I have answered my first question. In the UK, daylight savings time starts on 29/04/2020. Since the dates entered via the Google Form have no time associated with them, the time appears to be stored as 00:00:00, or midnight. I assume that what is happening is that the adjustment for daylight savings time (1 hour) is subtracting an hour from this time, thereby rolling it back to the day before.
My final question stands: is there a means to reliably prevent this error from occurring rather than manually checking for inaccurate dates (or programming in daylight savings time dates)?

Linking to OWA Calendar - Passing a Time Zone

I am trying to prefill a create event link to Microsoft OWA.
This works:
https://outlook.live.com/owa/
?path=/calendar/action/compose
&subject=TestEvent
&location=testlocation
&startdt=2018-02-29T19:00:00
&enddt=2018-02-29T20:00:00
&body=Testtext+my+test+text
Test it here
But I did not find a way to set a timezone, since for some reason that is not documented.
Is there a way to set the timezone of startdt and enddt?
I already tried appending a Z to the date, as this works in Yahoo and Google Calendar links (it tells the application that the timezone is UTC).
I have also been unable to discover how to set a timezone for the OWA calendar event link. However, I have discovered that you can specify a UTC offset value within the link. There are two drawbacks to this method though. The first drawback is that you have to account for daylight savings time on your end, because the UTC offset changes. The second is that the end user needs to have their timezone set correctly for them to see the correct time.
How you specify the UTC offset within the link is by adding the offset to the end of the startdt and enddt parameters in the format of + or - hh:mm. For example, let's say the event was set for March 27, 3pm, in the Eastern standard time zone. In the US, daylight savings is active on March 27, so the UTC offset would be -4 for the eastern US. The startdt parameter should then be 2018-03-27T15:00:00-04:00. Same goes for the enddt parameter.

Add Datetime rows to a datatable in the DataTableBuilder for Google Scripts

I've built an intraday macroeconomic forecast system in R. It uses intraday market data to update an forecast. Basically, I have a forecast series that looks like financial market data.
I want to show these data using a Google Chart in the Google App Script platform. To keep the datatable small (and thus load time down), I only want to plot intraday values for the five most recent days. For older days, I want to save only the last forecast of the day. That is, I want to have a time series plot with two frequencies of data which the user can choose from.
Here's and example of how I write the data from R (columns separated with "|"):
OBSlatest.forecast|freq
2014-03-10 14:45:00 EDT|4.09662|D
2014-03-11 15:00:00 EDT|4.10075|D
2014-03-12 14:57:00 EDT|4.08862|D
2014-03-13 14:57:00 EDT|3.998|D
2014-03-14 15:00:00 EDT|3.9843|D
2014-03-10 09:30:00 EDT|4.13823|I
2014-03-10 09:33:00 EDT|4.13468|I
2014-03-10 09:36:00 EDT|4.14078|I
I'm currently translating this table into Google App Script with
var data = Charts.newDataTable()
// Set data table columns
.addColumn(Charts.ColumnType.DATE, "Time")
.addColumn(Charts.ColumnType.NUMBER, "Forecast")
.addColumn(Charts.ColumnType.STRING, "Frequency")
// Fill in rows
.addRow([new Date(2014,3,13,14,57, 0),3.998 ,'D'])
.addRow([new Date(2014,3,10,9,30, 0),4.13823 ,'I'])
// More rows, but they all look like this, either a 'D' or 'I' at end
I've got a rough script up now that uses a category filter so that the user can choose to show either the daily frequency 'D' or intraday frequency data. However, I seem to be using the Date() function wrong. My data are all out of order and the dates don't match what I've loaded. My understanding the of Date() function's arguments is: Date(year, month,day,hour,min,sec), yet I only seem to be able to get the year to show up right in my chart. For example, the first row I'm adding in my code above yields "13 apr 2014 11:57:00" when my expectation is that it'd give "13 mar 2014 13:30:00"!
Nearest I can tell is that it is subtracting three hours from my time and one month from my month. Any ideas what's going on? This approach works fine for an HTML implementation of Google Charts, which I have up at: EfficientForecast.com
Thanks for any help!
The month parameter is zero-based, so subtracting one is the correct/expected thing to do. Check the MDN docs.
About your hour issue, I can not reproduce it. So I imagine it is something specific to your system. Please check what your Google Drive timezone setting is, then this Apps Script's setting and lastly your OS timezone setting. I imagine this is happening because some of these configurations are not matching.

data type to use in mysql for timezones

I store a date/time in my database that is UTC. I'm working to add conversion of this once a user selects a timezone so it shows local time for them. Basically the user selects from a form:
<select name="DropDownTimezone" id="DropDownTimezone">
<option value="-12.0">(GMT -12:00) Eniwetok, Kwajalein</option>
<option value="-11.0">(GMT -11:00) Midway Island, Samoa</option>
<option value="-10.0">(GMT -10:00) Hawaii</option>
...
I can make the option value anything I want but an easy to remember one is as above. What data type would I use for mysql? Does it really matter in this case? Would TINYINT do? Maybe using an ENUM would be a good idea?
Any suggestions would be appreciated.
The scheme you're proposing (storing time zones as an integer offset from GMT) may fail for the following cases:
India, which is on UTC + 05:30 (not an integer number of hours).
Kiribati, which is on UTC + 14:00 (over 12 hours).
Distinguishing British Time and GMT. (The former uses Daylight Saving Time; the latter is not.)
Distinguishing between some pairs of countries which use the same GMT offset, but which switch at different times of the year.
For full time zone support, I'd recommend using the zoneinfo database and storing time zones as strings (e.g, "America/New_York").
Although this is very old. But for anybody still looking for the solution. I used
date-fns with time zones. I am using reactjs with node.js . Only had to add one extra column to the table - and always store time in UTC format only - and the corresponding zone in the additional column.
https://date-fns.org/v2.23.0/docs/Time-Zones
import { zonedTimeToUtc } from 'date-fns-tz'
const date = getDatePickerValue() // e.g. 2014-06-25 10:00:00 (picked in any time zone)
const timeZone = getTimeZoneValue() // e.g. America/Los_Angeles
const utcDate = zonedTimeToUtc(date, timeZone) // In June 10am in Los Angeles is 5pm UTC
postToServer(utcDate.toISOString(), timeZone) // post 2014-06-25T17:00:00.000Z, America/Los_Angeles
And for the scenario of timezones - list. https://www.npmjs.com/package/countries-and-timezones

Date/Time stored as floating point, which algorithm is used?

I'm have access to a 3rd party application's database, and I see a field called "date" which stores date/time values as floating point numbers, but I'm not sure how this floating point number is mapped to a date/time. There is no documentation for this database.
Here is some sample data:
date-field actual-date-time
253507382.168744 1/12/09 6:43 PM PST
253507480.136126 1/12/09 6:44 PM PST
253508091.838982 1/12/09 6:54 PM PST
256703604.015055 2/18/09 6:33 PM PST
256704413.484674 2/18/09 6:46 PM PST
Note: I had to enter these values manually so there's a slight chance they may be off a bit. If you would like to see more data, let me know and I'll add more.
I'm hoping someone is familiar with storing dates in this format and can let me know how to get a date/time given a floating point number.
If you look at the change in the numbers over the 10 and 13 minute intervals, you'll see that it's about 60. Therefore I conclude that it's a count of the number of seconds from a base date.
I think the base date is 1/1/2000 or 1/1/2001.
Edit: The base date appears to be 1/1/2001, and the time appears to be adjusted as well - it's probably UTC with your local time offset added.
If you subtract any of the two points you'll see that the values represent the number of seconds, at microsecond accuracy. It should be easy to work out the base date where the clock "started". On Unix and related systems this is January 1st, 1970.
The timestamps are 'number of seconds elapsed since 00:00 on January 1st 2001'. It's not a common date format but at least it should be easy to work with now you know what it represents!