I am working with Google apps script and have a working function that sends emails based on a custom menu. The function that sends them is using a getRowsData() function to gather all the columns as objects, concatenating those objects into strings, and sending them via the htmlBody parameter, like this:
MailApp.sendEmail({
to: recipient,
subject: emailSubject,
htmlBody: message,
});
The message variable holds text and concatenated variables, with HTML formatting applied to construct the email. There is a portion that creates an Ordered list based on some other variables, and one of them is the date, which is pulled from a column within the sheet:
var message = "Other stuff here....Then"+
"<ol>"+
"<li>"+desc+"</li>"+
"<li>"+actions+"</li>"+
"<li>"+datesPer+"</li>"+
"<li><strong>Additional notes:</strong>"+actionNotes+"</li>"+
"</ol>"+
"More stuff below....";
When the email is sent, the datesPer variable prints out a bunch of other characters after the actual date. I'm assuming it's because the form attached to the sheet is inserting a datestamp:
3. Date: Tue Nov 08 2016 00:00:00 GMT-0800 (PST)
The 00:00:00 GMT-0800 (PST) is what I would like to change, with the zeroes using a regular time format (8:00 AM for example) and everything after that deleted. The array storing the dates has them formatted the way that they are coming out in the email, so this is a case of me telling the code exactly what I want, without telling it exactly what I want. I saw a Utilities.formatDate() class in the documentation, but it doesn't appear that I can call this into the script editor in sheets (Or I'm going about it wrong.)
If I missed a setting in the form, and this is just a checkbox somewhere, please educate me :) If it's something I can fix with code, I'd love some suggestions.
Thanks!
You can use javascript Date object functions to get the time from your date string.
You can find more details about it here: http://www.w3schools.com/js/js_date_methods.asp
Your script should have a line like this:
datesPer = "Date:" + TimeArray[0]
You can modify the date by creating a new Date object using the value from the array like so
var dateFromSheet = new Date (TimeArray[0])
var day = dateFromSheet.getDay() //(Returns 0- Sunday, 6 - Saturday)
var time = dateFromSheet.getHour() + ":" + dateFormSheet.getMinutes()
The values that you get from the above can be formatted to your liking and pass it to datesPer variable.
Related
I make a bot which is connected with spreadsheets with Webhook.
I have a cell with a date formatted like 'dd MMMM', e.g. "03 september". It is got from a certain amount of milliseconds which is equal to 03.09.2020 00:00:00 GMT+3.
I want to use this exact value ("03 september") as a poll option.
You can see my code below.
If I use it as it is, poll option is somehow converted into the value
"2020-09-02T21:00:00.000". If I map all the dates into Strings before sending it into JSON then this option looks like "Thu Sep 03 2020 00:00:00 GMT+0300 ... ".
How can I keep it looking simple in telegram?
UPD: I figured that Utilities.formatDate() is a proper solution for this, but still I don't know how to format month name into russian locale.
function doWork() {
var availableDates = scheduleSheet.getRange(1, 1, 1, 5).getValues()[0];
//var stringDates = availableDates.map(function(date) {return String(date)});
sendPoll(chatId, availableDates);
}
function sendPoll(chatId, options) {
var data = {
method: "post",
payload: {
method: "sendPoll",
chat_id: String(chatId),
question: "Some question:",
options: JSON.stringify(options),
is_anonymous: false,
allows_multiple_answers: true,
reply_markup: JSON.stringify(REMOVE_KEYBOARD)
}
};
UrlFetchApp.fetch('https://api.telegram.org/bot' + token + '/', data);
}
Posting this for documentation purposes.
As Tanaike suggested, in order to keep the displayed formats when retrieving dates (or any value) from sheet cells in Apps Script, use getDisplayValues() instead of getValues():
Returns a two-dimensional array of displayed values, indexed by row, then by column. The values are String objects. The displayed value takes into account date, time and currency formatting, including formats applied automatically by the spreadsheet's locale setting.
I have a method which sets the created property of my token, like so:
const token = new Token();
console.log(moment().toDate());
token.created = moment().toDate().toJSON();
There's something I just can't get my head around and it's really confusing me.
The line console.log(moment().toDate()); prints Tue Sep 01 2020 14:11:39 GMT+0100 but when I check the property created on debugger although it's using the same moment object and methods (except from calling toJSON()) it produces a date time which is an hour behind like so: 2020-09-01T13:11:39.179Z
I store the moment date as a string in the created property because this will be stored in localStorage.
Does anyone know the reason for this?
The times are the same. Look closely.
One marks the time zone as Z, the other as GMT+1.
Those time zones are 1 hour apart.
You can specify the time zone
I am building a self-depreciating list of dates and am using Date.parse() to convert rich text into a timestamp. Right now, we have a system where the user enters the date themselves, and I use a token on the backend to pull it through to that specific page.
I am trying to 'protect the user' from entering a wrong date format.
Currently, if they enter January 12th, 2016 it won't be able to parse and create a timestamp due to th. However, if they enter January 12, 2016 it can create a timestamp.
Is there a way to replace these ordinal numbers on a dynamic string? I've tried a simple jquery find/replace, but have had no luck with getting it to remove the ordinal date texts.
What I've tried:
$('.my-button').each(function() {
console.log($(this).text());
var text = $(this).text().replace('st, ', '');
$(this).text(text);
});
Any ideas on a solution, or a way to make Date.parse(): accept these extra characters?
For the simple case of removing an ordinal from a date string like "January 12th, 2016", you can use a regular expression like:
var re = /(\d{1,2})[a-z]{2}\b/i;
['January 12th, 2016','January 1st, 2016','January 2nd, 2016','20th February, 2015'].forEach(
function(s) {
document.write('<br>' + s.replace(re,'$1'));
}
);
However, parsing strings with Date.parse (and the Date constructor, they are equivalent for parsing) is strongly recommended against. Use a parser and define the format, do not leave it to chance.
There are libraries like moment.js, however it may be too big for your requirements. There are other dedicated parsers (check on GitHub), or if you only need to support one format, write one yourself. It only requires three or four of lines of code.
I found some code here on Stack Overflow that does exactly what I want, which is to take a GMT time string and convert it to the local time on the user's browser. Awesome.
However, I'm stuck on what should be a very small thing. When I display the time, I want the user's current local timezone to display along with the time. The goal is to output a string that looks something like:
2014/02/19 15:12 (PST)
I've looked at the parameters for the Javascript Date() function, but, unless I'm blind, I don't see one that outputs the user's timezone. There's getTimezoneOffset(), which returns a number, but not the code for the timezone.
I've got all the rest of the time displaying fine, except for that last part where I want it to say PST (or GMT or JST or wherever the user is). Is there a way to do that?
It can be done creating a date and then performing some operations on it. If you take a look at format in which newly created Date object is created it is e.g. like:
Wed Feb 19 2014 07:29:26 GMT+0100 (Central European Standard Time)
Now you may simply take the whole name like:
var myDate = new Date();
var userTmzn = myDate.substring(myDate.lastIndexOf('(')+1).replace(')','').trim()
and this should give you this in userTmzn
Central European Standard Time
Now to make it neat and have an abbreviation you may try some more operations:
// Take the part with timezone name and strip it from trailing ')'
var fullName = myDate.split("(")[1].replace(")","");
// Split into words
var words = fullName.split(" ");
// Take just first letters
var timezoneCode = "";
for(i = 0; i < words.length; i++)
{
timezoneCode += words[i].charAt(0);
}
That should give you (following the same example) this in timezoneCode variable:
CEST
This is highly custom, not a ready solution. You should verify in the code that default date's toString() returns date in TIME FORMAT, you should test on various browsers, etc. This is just a clue.
I'm wondering if it's possible to use AngularStrap's datepicker without it keeping the user's locale's timezone information. In our application we want to handle Contract objects that have an expiration date.
When adding or editing the contract object, there is a datepicker field for selecting the date. The following thing happens:
The user selects the date (e.g. 2013-10-24)
Angular binds the javascript date object to the ng-model field
The binded date object is in the user's timezone (e.g. GMT+3)
The user submits the form
The date gets sent to the server using Angular's $http service
In step 5 the date is converted to UTC format. The selected date was GMT+3 2013-10-24 at midnight, but the UTC conversion changes the date to 2013-10-23 at 9pm.
How could we prevent the conversion, or use UTC dates during the whole process? We don't want the contract's date to change based on the user's local timezone. Instead, we want the date to be always 2013-10-24, no matter what timezone.
Our current solution was to make small changes to the AngularStrap library so that the date won't change when sent to the server.
If we could get the user's selected timezone in the server, we could make another conversion there, but the server doesn't have that information.
All ideas are appreciated!
The issue isn't AngularStrap. Its just how javascript dates work and how JSON formats them for transmission. When you turn a javascript date object into a JSON string, it formats the string as UTC.
For example, I'm in Utah and it is now 07:41 on 2013-10-24. If I create a new javascript date and print it to the console it will say:
Thu Oct 24 2013 07:41:19 GMT-0600 (MDT)
If I stringify that same date (using JSON.stringify(date), I get:
"2013-10-24T13:41:47.656Z"
which you can see is not in my current timezone, but is in UTC. So the conversion is happening just before the form gets sent to the server when it gets converted from a javascript object to a JSON string.
The easiest way to do it would be to just change the date to a string of your own choosing prior to sending the date to the server. So instead of letting JSON change the date to UTC, (assuming you don't care about the time of day) you could just do something like this:
var dateStrToSend = $scope.date.getUTCFullYear() + '-' + ($scope.date.getUTCMonth() + 1) + '-' + $scope.date.getUTCDate();
That will give you a UTC-based string that looks like '2013-10-24' and then you can send that to the server, instead of the JSON format which includes the time info. Hopefully that helps.
UPDATE: As #Matt Johnson said, there are two ways to do it. You said: How could we prevent the conversion, or use UTC dates during the whole process?. If you want to use UTC, then use my above explanation. If you want to just "prevent the conversion", you could use the following:
var dateStrToSend = $scope.date.getFullYear() + '-' + ($scope.date.getMonth() + 1) + '-' + $scope.date.getDate();
A bit late but I spent my afternoon on this and someone might find it useful.
Another way to do this declaratively is to use the dateType, dateFormat and modelDateFormat attributes. Set these in either the config or the HTML e.g
angular.module('app').config(function ($datepickerProvider) {
angular.extend($datepickerProvider.defaults, {
dateFormat: 'dd-MMMM-yyyy',
modelDateFormat: "yyyy-MM-ddTHH:mm:ss",
dateType: "string"
});
});
DateFormat is the format the date will be displayed to the user in the date picker while modelDateFormat is the format it will be converted to before being bound to your model.
I also had default values coming from the server which I needed to be bound to the datepicker on page load. I therefore had to update the format the server serialized dates in JSON to match the modelDateFormat. I am using Web API so I used the below.
var jsonSettings = Formatters.JsonFormatter.SerializerSettings;
jsonSettings.DateFormatString = "yyyy-MM-ddTHH:mm:ss";
The "Angular way" is to use the $filter service to format the date returned by the datepicker.
Example (HTML):
{{inpDate | date: 'dd-MM-yyyy'}}
Example (JS):
$scope.processDate = function(dt) {
return $filter('date')(dt, 'dd-MM-yyyy');
}
Plunker here