Get SQL Server query results as JSON

The simplest way to get query results as JSON is to use FOR JSON PATH in the query (note: this was added in SQL Server 2016): It returns the results as a single JSON string with one JSON object per row: Note: SQL Server returns the JSON without indenting. All examples in this article show … Read more

The JSON value could not be converted to System.DateTime

When you’re using System.Text.Json to deserialize a DateTime value, if the value isn’t in the format it expects, then it’ll throw a JsonException. It expects datetimes to be in the ISO-8601-1:2019 format (for example: 2021-07-12T12:35:34+00:00). For example, the following code is trying to deserialize a DateTime value in an unexpected format: This’ll throw the following … Read more

C# – Parsing a DateTime from a string

You can convert a string to a DateTime (parse) with one of these methods: I’ll show examples of using both methods for parsing various DateTime formats. Using DateTime.Parse() DateTime.Parse() can handle parsing a wide variety of culture-specific standard DateTime formats and the ISO-8601 format (which is the default date format for JSON serialization). By default, … Read more

C# – How to use format strings with string interpolation

Interpolated strings have the following structure: {variable:format}. Typically you exclude the format, so they normally look like this: $”My name is {name}”. Here’s how to use format strings with an interpolated string: This outputs the following: This is the equivalent of using string.Format() like this: Read more about why you should use string interpolation instead … Read more

C# – How to test that your code can handle another culture’s date format

Let’s say you have code that converts a string to a DateTime with DateTime.Parse(): By default, DateTime.Parse() uses CultureInfo.CurrentCulture to figure out the date format. The current culture ultimately comes from your OS settings. So when you run this code on a computer that is using the en-US locale, the current culture will automatically default … Read more