Unexpected (string, string, string) error when running the script - google-apps-script

I'm running a script to generate a certificate and it runs through and creates the certificates becomes up with this error:
Error
Exception: The parameters (String,String,String) don't match the method signature for Utilities.formatDate.
createCertificates # Code.gs:51
The code in question that is in line 51 is:
empSlide.replaceAllText("<<Date>>", Utilities.formatDate(date, Session.getScriptTimeZone(), "dd, MMMM, yyyy"));

The method Utilities.formatDate(date, timeZone, format) requires the following parameters:
Name
Type
Description
date
Date
a Date to format as a String
timeZone
String
the output timezone of the result
format
String
a format per the SimpleDateFormat specification
In your scenario the first parameter is given as a String instead of a Date, and that generates the error. The variable date, as shown in line 51, is a string.
I am going to assume that you store the date in a string like "YEAR-MONTH-DAY", please correct me if I am wrong. In that case you can easily fix the script by calling the Date constructor like this:
var date = new Date("1994-11-30");

Related

GOLANG json to Protoc with LocalDateTime, not DateTime

I'm working on a middleware using golang.
I'm consuming a REST-API which returns a Date in form of a LocalDateTime (e.g. "created": "2022-01-09T00:00:00",) and it should get mapped into an protoc message with the data class google/protobuf/timestamp.proto as we don't want to do the converting in the frontend. But apparently the timestamp.proto only supports DateTime with a timezone (so like that "created": "2022-01-09T00:00:00Z...") but as its an external API I'm consuming I cant change their datatype to DateTime. Does anyone know how to find and elegant solution without doing the complete mapping/unmashalling process manually?
That's the protoc message:
google.protobuf.Timestamp created = 7 [json_name = "created"];
That's the unmashaller we're using:
err = protojson.Unmarshal(body, protoMessageClass)
That's the error I'm getting:
ERROR: proto: (line ...): invalid google.protobuf.Timestamp value "2021-12-07T00:00:00""
First convert the time you receive as a string to a time.Time object:
t, err := time.Parse("2006-01-02T15:04:05", val)
Here "2006-01-02T15:04:05" represents the layout you expect.
Then you can use timestamppb built-in function to create a protobuf timestamp from a time.Time object:
tpb := timestamppb.New(t)
If you need the opposite, you can use AsTime from timestampb.Timestamp type and then format from time.Time object to make a string.

"Invalid object type conversion" error when trying

This code is supposed to prefill the date on google form, but I get an error:
Exception: Invalid object type conversion: DATE. (row: 13, file: Code)
function doGet(){
//open your form
var form = FormApp.openById("1m89CzaTzP5mIUvwdHbjOvaIoEWJ54N3vVf0LBl4RFIo");
//get the questions
var questions = form.getItems();
//get the question where you want to prefill the date as an answer, e.g. first question
var question1=questions[0];
//get the current date
var time=Utilities.formatDate(new Date(), "GMT+2", "dd-MM-2000");
//prefill form with current date
var prefilledTime=form.createResponse().withItemResponse(question1.asTextItem().createResponse(time));
//Get the link to the prefilled form
var URL=prefilledTime.toPrefilledUrl();
//redirect to the prefilled form URL dynamically created above
return HtmlService.createHtmlOutput("<script>window.top.location.href=\"" + URL + "\";</script>");
}
getItems method returns an array of generic Item instances that need to be converted to their respective types, as contrary to what one might expect, createResponse method has different signatures for each Item type:
DateItem and DateTimeItem expect a Date as the only parameter
Duration expects 3 numbers (docs say Integer)
CheckBoxGridItem wants a matrix of strings (string[][] in docs)
CheckboxItem and GridItem only need a string array
MultipleChoiceItem accepts a string, as does ParagraphTextItem and, of course, so does TextItem
ScaleNumber is happy with a number
TimeItem - 2 numbers, representing hours and minutes
What's more, the types are fixed, so the only option available is converting from Item to the original item type (for example: DateItem > Item > DateItem). If you try to convert a DateItem to TextItem (which is exactly what you did), an "Invalid type conversion" error is thrown.
formatDate method returns a string and judging from the screenshot you provided, the item is of type DateItem, therefore you need to call the asDateItem method, not asTextItem and pass the new Date() directly as the method signature suggests.

Ballerina json datetime value

i have to index documents to elasticsearch to an index which has a date field mapping and i'm trying to build a json with this date value, but ballerina says this seems not possible.
I thought about storing this date value into an xml and after that to convert it to a json but xml has the same problem (i thought this might be a trick...).
I tried to store it into a string and after that to extract the json payload from that string but it gives me this error:
error: {ballerina/io}GenericError message=unrecognized token 'date=time=1591128342000'
I thought about dealing with this string to date conversion from inside elasticsearch but i would like to keep this scenario as the last one. I don't like it, beacause i have to do some queries based on timestamp after and storing date as a string would give me additional problems
So is there any way to trick ballerina in order to achive this json containing a date value ?
-----here is snapshot of the code giving me the error-----
It says:
incompatible types: expected 'json', found 'ballerina/time:Time'
JSON is a text format that is completely language independent (see e.g. json.org).
time:Time is a Ballerina language specific type JSON knows nothing about. Because there is no implicit conversion (for a good reason) one have to provide the conversion.
In this case you most likely want to convert time:Time to a ISO 8601 string presentation with time:toString.
The following code (Ballerina 1.2):
import ballerina/io;
import ballerina/time;
public function main() {
var btime = time:currentTime();
var j = <json> {
time: time:toString(btime)
};
io:println(j.toJsonString());
}
Correctly prints:
{"time":"2020-06-03T08:39:07.897+03:00"}
Maryam Ziyad has written a good introduction to Ballerina's JSON support.
The following code is updated for Ballerina Swan Lake Update 1 (2201.1.0) to show how to convert a Ballerina UTC time (time:Utc) to JSON representation. Note that it's also possible to use localized time (time:Civil) but that is no different from time to JSON conversion point of view.
One can read more about Ballerina time handling from the documentation of time module.
import ballerina/io;
import ballerina/time;
public function main() {
time:Utc now = time:utcNow(3);
json j = {
time: time:utcToString(now)
};
io:println(j.toJsonString());
}
That correctly prints:
{"time":"2022-07-20T06:03:46.078Z"}

Angular 5 not parsing timestamps correctly from json

I have a working (in production) web app (material + angular 5 (5.2.11)). Also I've an API written in .dot core 2 (C#) using Nancy FX and newtonsoft json.
Problem:
DB (mariaDB running on Ubuntu Server): I have this value: 2018-05-16 20:42:36 on a record.
Calling the endpoint yields the correct JSON:
{"timestamp":"2018-05-16T20:42:36Z"}
(the other fields were removed for sanity)
On Angular app I use:
... return this._http.get(this.endpoint + '/' + uuid, { headers:
this._getHeaders }).catch(this.handleError);
Where <T> represents a model that includes timedate: Date; as a property.
Using the service:
this._dataService.getByUuid(uuid).subscribe(result => {
console.log(result);
});
gives:
Object { timedate: "2018-05-16 08:05:36" }
So, the time lacks of AMPM format and I can't display it correctly. {{element.timedate | date: 'dd/MM/yyyy HH:mm' }} does nothing since timedate is just that, a bare string.
What have I tried:
Implementing a different format in JSON output (in NancFx API)
Adding a HTTP INTERCEPTOR
Reading this
Declaring the properties as Date, String
Problem is with any datetime field. The JSON is always on point and so the database.
Any help is appreciate
JSON doesn't have a Date type (only arrays, numbers, string, object, null and undefined), so the converter from JSON to TypeScript cannot know whether it's a date or a plain string.
You need to parse (Date.Parse(yourString) or new Date(yourString)) the Date property everytime your object is deserialized.
** Date.Parse and the Date constructor can take in a Date as well as a string so you don't really have to type check the value before using them.*

Realm format date JSON swift

I had JSON with a date "date_use" :
{"expense":
{"id":1,
"amount":123.3,
"date_use":"2015-07-04T00:00:00Z"}
}
I had an error on date format when I execute this code :
self.realm!.create(Expense.self, value:json["expense"].object, update: true)
Error :
Terminating app due to uncaught exception 'RLMException', reason:
'Invalid value '2015-07-04T00:00:00Z' for property 'date_use'
My question is : What is the good date format for Realm?
The problem here is not the particular date format, but that JSON doesn't support a native date type at all. So you have to serialize dates to a string format. Using RFC 3339, like you have to deal with, is generally a good choice because it avoids ambiguities, so you can stick with that.
Realm's create method doesn't expect deserialized JSON, but a dictionary representation of your object. This expects that you have done already the preprocessing step of transforming date string representations back to Cocoa's native type NSDate. This isn't done automatically because there are date formats, which are ambiguous (unlike yours), which e.g do not provide information about the timezone.
Good news is there are excellent third-party libraries e.g. Realm-JSON, which make it a whole lot easier to deal with that. It brings built-in support for that.
This would also allow to map the property naming scheme returned by your API, e.g. date_use to names which conforms to the more broadly used camel-case dateUse.
If you don't want to introduce another dependency just for that use case, you can use and configure NSDateFormatter to parse dates conforming to your particular subset of the RFC 3339 standard, assuming they always use UTC as timezone, marked through the Z suffix.
// Setup the RFC 3339 date formatter
let rfc3339DateFormatter = NSDateFormatter()
let enUSPOSIXLocale = NSLocale(localeIdentifier: "en_US_POSIX")
rfc3339DateFormatter.locale = enUSPOSIXLocale
rfc3339DateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"
rfc3339DateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
// Convert the RFC 3339 date time string to an NSDate
var json: AnyObject! = nil
var value = json["expense"] as! [String : AnyObject]
let date: NSDate?
if let dateString = value["date_use"] as? String {
date = rfc3339DateFormatter.dateFromString(dateString)
} else {
date = nil
}
value["date_use"] = date
// Create your object
self.realm!.create(Expense.self, value: value, update: true)