Skip to content

Instantly share code, notes, and snippets.

@mhawksey
Forked from erickoledadevrel/Code.js
Last active June 14, 2022 05:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mhawksey/85ab5e914174e6e6b8e927fae2608e00 to your computer and use it in GitHub Desktop.
Save mhawksey/85ab5e914174e6e6b8e927fae2608e00 to your computer and use it in GitHub Desktop.
Formatting date/time values using the user's timezone in Apps Script.
/**
* @file A sample showing how to format date/time values in Apps Script so that they appear in the
* user's timezone. View a working version here:
* https://docs.google.com/spreadsheets/d/1t_ur0wMw80AXaFkpBXmYclLfGm_kDccYcD5LAGoBkrQ/edit
*/
/**
* Add menu item after the spreadsheet opens.
*/
function onOpen() {
SpreadsheetApp.getUi().createMenu('Sample')
.addItem('Show sidebar', 'showSidebar')
.addToUi();
}
/**
* Show the sidebar.
*/
function showSidebar() {
var page = HtmlService.createHtmlOutputFromFile('Page').setTitle('User Timezone Sample');
SpreadsheetApp.getUi().showSidebar(page);
}
/**
* Gets the timezone stored for the user.
* @returns {string} The timezone of the user or null if not set.
*/
function getUserTimezone() {
return PropertiesService.getUserProperties().getProperty('timezone');
}
/**
* Sets a timezone for the user.
* @param {string} timezone The timezone of the user.
*/
function setUserTimezone(timezone) {
PropertiesService.getUserProperties().setProperty('timezone', timezone);
}
/**
* Formats a date using the user's timezone. Throws an exception if no timezone has been set
* for the user.
* @param {Date} date The date to format.
* @param {string} format The date format to use.
* @returns {string} The formatted date.
*/
function formatDateForUser(date, format) {
var timezone = getUserTimezone();
if (!timezone) {
throw 'Error: Timezone not set.';
}
return Utilities.formatDate(date, timezone, format)
}
/**
* Gets the current time as a string.
* @return {string} The current time.
*/
function getCurrentTimeAsString() {
return formatDateForUser(new Date(), 'yyyy-MM-dd hh:mm:ss a');
}
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons.css">
<div class="sidebar">
<button id="show">Get current time from server</button>
<pre id="time"></pre>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function() {
// Set the timezone offset every time the sidebar loads.
google.script.run.setUserTimezone(Intl.DateTimeFormat().resolvedOptions().timeZone);
// Setup the button handler.
$('#show').bind('click', function() {
google.script.run.withSuccessHandler(function(time) {
$('#time').text('Time: ' + time);
}).getCurrentTimeAsString();
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment