iTranslated by AI
Be Careful When Handling Date and Time in Azure Functions Cosmos DB Trigger
Azure Functions allows you to use various triggers.
Among them is the Cosmos DB Trigger.
I thought that when this trigger fires, the data from Cosmos DB would be passed directly to Azure Functions as-is.
However, it seems that if you input a date and time as a string in ISO 8601 format, it is automatically converted to UTC.
I was quite startled to find that the time had shifted back by 9 hours without me realizing it.
Trying it out
- Create a Cosmos DB and Azure Functions instance as appropriate.
The code for the functions can be the default template to keep things simple:
module.exports = async function (context, documents) {
if (!!documents && documents.length > 0) {
context.log('Document Id: ', documents[0].id);
}
}
- Create data in Cosmos DB with an arbitrary ISO date/time as the id:
{
"id": "2021-04-28T00:00:00+09:00",
}
- Look at the Azure Functions logs:
Document Id: 04/27/2021 15:00:00
Yes. The time has changed by 9 hours.
In fact, the format has changed.
It seems like it automatically converts it if it's a date-formatted string.
Running it locally
Azure Functions Core Tools is provided for local debugging of Azure Functions.
Let's try running it using that.
Document Id: 04/28/2021 00:00:00
The results are different...
Conclusion: I'm not really sure
It's problematic when information stored in the DB is converted automatically. The TimeZone information has disappeared from the string.
And what's even more problematic is that the execution results differ between local debugging and running in the cloud. This only leads to bugs.
I thought that if I changed the execution environment's TimeZone, the values I could retrieve might change accordingly, so I tried setting the environment variable WEBSITE_TIME_ZONE, but the result remained the same.
If anyone knows a good workaround, please let me know.
Discussion