C# – Convert DateTime to string

When you want to convert a DateTime to a string, use ToString(). By default, this converts the DateTime to a string using the current culture’s date/time format (from the OS). In most cases, you’ll want to specify the format to use. You can do this by passing in a format string consisting of format specifier … Read more

C# – Get the current date and time

Use DateTime.Now to get the current date/time, like this: This outputs the system’s current date/time: Note: By default, it uses the current culture’s date format (from the OS). This is showing the US date format – MM/dd/yyyy. DateTime.Now is the local date/time from the system where the code is executing. Keep that in mind if … Read more

C# – Get the last day of the month

The last day of the month is the number of days in that month. To get the number of days in a month, use DateTime.DaysInMonth(year, month): This outputs the following: Notice that it handles leap years (2024) appropriately. Using the number of days in the month, you can get the last day of the month: … Read more

C# – How to use JsonConverterAttribute

You can use JsonConverterAttribute (from System.Text.Json) to apply a specific JsonConverter to a property. Apply this attribute on a property and specify the JsonConverter type to use, like this: In this example, it’s applying ExpirationDateConverter (a custom JSON converter) to handle the ExpirationDate. For reference, here’s ExpirationDateConverter’s definition: Now serialize the object to JSON: Here’s … Read more

C# – How to use JsonConverterFactory

Let’s say you want to serialize the four datetime types – DateTime, DateTime?, DateTimeOffset, and DateTimeOffset? – in the same way. You want to serialize them to use the US date style (ex: 7/14/2021). There are two main ways to accomplish this: 1) Create a custom JsonConverter for each type or 2) Create a JsonConverterFactory … Read more