Date formatting from Google Spreadsheet to Telegram bot - javascript

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.

Related

How to "use" TIMESTAMP postgres data type

I have saved a datetime value created by Luxon into a postgres database column, of type TIMESTAMP(3). I want to then use that value, convert it into other time zones, etc. However, I can't seem to figure out how to "use" it.
I created the object using the following
const { DateTime } = require("luxon");
const myDate = DateTime.now().toUTC().toISO()
I then inserted it into a postgres database, into a column of type TIMESTAMP(3).
I extract it out of the database using a query. When I log it, it says its value is:
console.log(extracted_date); //=> "2021-12-27T09:57:16.184Z"
console.log(typeof extracted_date); //=> object
// The following return "unparsable" or undefined objects
DateTime.fromISO(extracted_date);
DateTime.fromObject(extracted_date);
I can find plenty of tutorials about how to insert dates into sql, but nothing on how to take that date object and actually do something with it. I want to, for instance, convert its time zone.
To use that date object you can initiate a new Date, like so:
console.log(extracted_date); //=> "2021-12-27T09:57:16.184Z"
const javascriptDate = new Date(extracted_date);
Than you can use it directly or with the luxon library.
console.log(javascriptDate.toGMTString()); // => "Mon, 27 Dec 2021 09:57:16 GMT"
console.log(javascriptDate.toISOString()); // => "2021-12-27T09:57:16.184Z"
console.log(javascriptDate.valueOf()); // => 1640599036184
This object core is actually, a value that represents milliseconds since 1 January 1970 UTC, and added to that are time and string parsing functions, generally speaking.
More Info
In some systems dates are store in the database as the value -
date.valueOf() - which make it clearer (for a developer) you have to manipulate it, and perhaps reduce problems of showing the wrong timestamp to users. In the other hand - you lose the readability. Another opion is using only UTC time in your system and convert the timestamp on client side or before presenting the data. The use of UTC will make sure all of your dates will have same language'.
If you want to read more about timestamp,
here are some references:
UTC vs ISO format for time
What is the "right" JSON date format?

How to query in order of custom date format in postgres?

I have a postgres table with a column "date" which is a string with the basic javascript date format:
"Tue Dec 29 2020 23:16:54 GMT-0800 (Pacific Standard Time)"
I am wondering if there is a way to query by date even though it's in a string format like that. In my node backend, I am currently doing this:
pool.query("SELECT * FROM table WHERE field1 = $1 ORDER BY date DESC LIMIT 10", [val1], (err, table) => {
if(err) {
return res.status(400)
done()
} else {
res.json(table.rows)
}
})
This appeared to be working at first but since adding more records it is not really working correctly. If there is a fix for this that doesn't involve redoing the date column, I would be infinitely grateful as I've already built out a lot of code around that date string format. Thank you in advance.
As the commenters have noted, you would be much better served by a timestamp column than a string column. However, if you can't change your schema, then you can convert your timestamp string to an actual timestamp before ordering by it, like this -
SELECT * FROM table
WHERE field1 = $1
ORDER BY to_timestamp(date, 'Dy Mon DD YYYY HH24:MI:SS') DESC
LIMIT 10

jQuery Ajax is adding timestamp on dates automatically

i have mysql query which return some data with dates. When i am requesting ajax request it add timestamp into my response.
Is there any way so it didn't added timestamp automatically on responses.
jQuery.ajax({
url: "/getdata",
type: "POST",
data: { },
success: function (result, textStatus, jqXHR) {
console.log(result)
}
});
var query = "SELECT SUM(`id`) as `total`,DATE(`log_date`) as `log_date` from `mytable` Group by `log_date`"
This is my response which is adding T18:30:00.000Z to end of the dates:
[
RowDataPacket { total: 1, log_date: 2020-11-09T18:30:00.000Z },
RowDataPacket { total: 10, log_date: 2020-11-10T18:30:00.000Z },
]
Thanks
This isn't a jQuery issue, it's a mix of JS and PHP and how you're storing your date values in the database.
JS Date objects have to contain a time value as well. There is no date-only data type. As such your response from PHP is interpreted with the date you return and a time of 00:00:00 is added to it to maintain validity.
I can see from your profile that you are in India so your timezone offset is +5:30, hence JS assumes the date is in your local format and tries to convert it to UTC by subtracting 5:30 from it. Therefore the resulting date is 1 day before the actual value at 16:30:00.
To fix this I would suggest you return your dates in full ISO8601 format, including time and offset, so there is no ambiguity that JS attempts to overcome.

JavaScript mail function - strip datestamp portion from string

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.

remove time from dates when shown on highchart

how can i remove the time from the date when shown on the highchart.the data (dates) are received from a twitter get request and saved into an array.
for (var i in array) {
dateArray.push(array[i].date);
}
highchart(dateArray);
an example of date shown on the graph: Sat,04 Aug 2012 19:35:02 +0000
The way I see it you have two options:
Only pass in the day value of the time for your categories. Involves processing on the backend.
Pull your data as-is and convert to Javascript time format, make your xAxis datetime type, set up your tickInterval to be one day, and run your chart.
Without know what your data looks like, what you are plotting on the yAxis, or what your expected outcome is it is really hard to say.
I recommend to go with option #2 because this is time based data.
EDIT: Based on your comments
You can first convert the string to a date object, and then format the date object to your liking using SimpleDateFormat.
SimpleDateFormat format = new SimpleDateFormat("EEE, MMM d yyyy");
String formattedDate = format.format(new Date(array[i].date));
dateArray.push(formattedDate);
You can find various date formats # http://blog.stevenlevithan.com/archives/date-time-format

Categories

Resources