C# – Get the current date and time

Here’s an example of how to get the current date/time: This outputs the current local date/time: Note: By default, it uses the current culture’s 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

WinForms – Date and time input

When you need to let the user select a date and/or time of day, you can use the DateTimePicker control: You can set the control properties in the UI or programmatically: If you don’t set an initial value, it’ll default to DateTime.Now (at the time the code is executed). The value the user picked is … Read more

C# – Configuring how long an HttpClient connection will stay open

When you use a single instance of HttpClient to send requests, it keeps connections open in order to speed up future requests. By default, idle connections are closed after 2 minutes, and otherwise will be kept open forever (in theory). In reality, the connection can be closed by the server-side (or other external factors) regardless … Read more

C# – Round up to the nearest 30 minutes

Here’s how to round a DateTime up to the nearest 30 minutes: When the time is 3:38 pm, it rounds to 4:00 pm. When it’s 5:03 pm, it rounds to 5:30 pm. When it’s exactly 2:00 pm, it’ll round up to 2:30 pm (note: see the What if you’re at the start of a 30 … Read more

C# – How to change the HttpClient timeout per request

It’s best practice to reuse the same HttpClient instance for multiple requests. When you’re using the same instance repeatedly, and you want to change the timeout per request, you can pass in a CancellationToken, like this: You can’t change HttpClient.Timeout after the instance has been used. You have to pass in a CancellationToken instead. There … Read more