'AWS Lambda Json Serializer is removing trailing zeros from milliseconds in a date time input
I have created an AWS lambda with C# .net core 3.1. This lambda takes a json object as input and one of the property names of the json object is a datetime. Look below for example input
{
"datetime": "2022-05-10T11:49:21.120Z",
"context": {
"user": "{\"Id\": \"user_id\"}"
}
}
C# lambda handler:
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
namespace LambdaFunction
{
public class Function
{
public async Task<JObject> FunctionHandler(JObject event, ILambdaContext context)
{
context.Logger.LogLine("Event Details: " + JsonConvert.SerializeObject(event));
string dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'";
var dateString = JToken.ReadFrom(jr)["AsOfDatetime"].ToString();
if (!DateTime.TryParseExact(dateString, dateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime dateValue))
{
throw new Exceptopm("datetime is not in UTC format");
}
}
}
}
I logged the input event inside the lambda and it printed the below value
{
"datetime": "2022-05-10T11:49:21.12Z",
"context": {
"user": "{\"Id\": \"user_id\"}"
}
}
The trailing 0
in datetime key's milliseconds before Z
(representing UTC) got removed 2022-05-10T11:49:21.120Z
to 2022-05-10T11:49:21.12Z
. I am trying to validate the input date time using DateTime.TryParse
as in the above code. But because the serializer is removing the trailing zeros and I'm using .fff
in the format, it's throwing error even when I give correct input if the input datetime has trailing zeros. I am going to later on store this date time in database and I want to store milliseconds to exactly 3 decimals. So, how can I prevent the serializer from removing the trailing zeros?
I'm sure we can write some code to add zeros at the end and achieve what we want but it just seems like extra work. Why do the trailing zeros even get removed by the serializer?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|