Getting the Current Time in C#: A Guide

Navigate to:

Getting the current time is an important task during programming, regardless of the programming language. C# is no exception. So, for all of you C# programmers out there who googled “C# current time” and learned about DateTime.Now but want to learn more—this post is for you.

In this blog we cover why it’s important to get the current time, and provide use cases. Then, we’ll dive into practical ways to obtain the current time and answer some frequently asked questions regarding the current time in C#. Let’s dig in.

Prerequisites

There aren’t many prerequisites to follow this post. If you want to test the code examples shown, you’ll need .NET installed and a code editor. As of this writing, the latest stable release of .NET is the 8.0 version, and that’s what I’ll be using. For the editor, I suggest Visual Studio Code, but any editor will work.

We’ll start with simple examples. If you are familiar with C#, you’ll do fine.

C# current time use cases

In programming, many valuable use cases require obtaining the current time, and optionally, the current date. That’s why being able to retrieve the current date is vital.

Usually, you’d want to get the current time in the following scenarios:

  • Recording when an important event happened for business purposes—e.g., a user placed an order, or a new shipment of products just made it to the warehouse.
  • Logging the details of an application error, when those include the current time and date.
  • Setting an alarm, reminder, or notification in the future, using the current date and/or time as a point of reference (e.g., “remind me in 4 hours”).
  • Displaying the current time on the UI (user interface) of your application.
  • Calculating how much time has passed since a given point in the past.

How can I get the current date and time in C#?

Let’s start exploring this whole “C# current time” thing. As you probably know, .NET represents a time and date using the System.DateTimestructure. To obtain a value of this type containing the current time, you use the following code:

DateTime now = DateTime.Now;

Having that value, you can access the TimeOfDay property on the object to get only the time:

Console.WriteLine(now.TimeOfDay);

That property returns a TimeSpan object that contains a value equivalent to the current time. Optionally, you can use the TimeOnly type to extract just the time of day:

TimeOnly time = TimeOnly.FromDateTime(now);

Console.WriteLine(time);

There are two more ways to obtain the current time in C#: DateTime.UtcNow and DateTimeOffset.Now. To understand why they exist, let’s first address the elephant in the room.

How can I get the current UTC time in C#?

From the previous example, you might be wondering: “current time” where? “Current time” in relation to what?

When you do DateTime.Now, what you get is a DateTime value whose Kind property is set to Local: This property can have three values: Unspecified, Utc, and Local. When the property is set to Local, that means that the DateTime value is “local” in regard to the machine where it originated from. However, this object has no concept whatsoever of time zones. In other words, it “knows” it was produced “here” but has no clue where “here” is!

This characteristic of “local” DateTime values means that, as soon as they leave the context of the computer where they were produced, they have very little usefulness. If you save them to a database, transmit them over an HTTP request, or transmit them in some way, the recipient won’t be able to reconstruct the original time zone from the value they received.

The solution for this conundrum is to always use universal time, or UTC, when you need to record the moment when something important happened. To retrieve the current time in UTC, you can do:

var utcNow = DateTime.UtcNow;

Console.WriteLine(utcNow.Kind); // displays "Utc"

You would then store or transmit the object. When it came time to display the data, you’d convert it to local time again:

var utcNow = DateTime.UtcNow;

Console.WriteLine(utcNow.Kind); // displays "Utc"

var localNow = utcNow.ToLocalTime();

Console.WriteLine(localNow.Kind); // displays "Local"

I’ve just said that DateTime objects have no concept of time zones. So, how does the ToLocalTime() method manage to convert the DateTime value to the correct local time?

Well, this particular object has no concept of timezones, but it uses information from the TimeZoneInfo class, which does. More on time zones later. For now, let’s cover the final way of retrieving the current time in C#.

C# current time with offset

You’ve just seen how to retrieve the current time in UTC. Generally speaking, that’s the way to go when your use case is to record the time of an event unambiguously. However, there’s a problem with that approach.

If you have a DateTime value whose Kind property is set to Utcand you save it to the database, and then you get it back, the Kind will be Unspecified. In other words, Kind information doesn’t round trip; it’s always lost when you leave the boundaries of a single machine.

So, using UTC if you’re using DateTime type relies on conventions. Everyone must be on the same page; everyone must be aware you’re using UTC. In the grand scheme of things, this isn’t the worst problem; it’s a widespread best practice that you should use UTC when recording events, so fortunately, adopting this convention shouldn’t give you much grief.

Wouldn’t it be nice to have more safety than that, though? Of course, it would, and that’s where the DateTimeOffset type comes in handy. This is a different type that, besides containing a date and a time, contains an offset, which is the difference, positive or negative, from UTC.

To retrieve the current date and time with the offset, do this:

DateTimeOffset now = DateTimeOffset.Now;

This is my current offset: How does this solve our problem? The SQL Server database contains a datetimeoffset type. A column with this type preserves the offset information that’s passed to it. That way, you wouldn’t have to rely solely on convention to use UTC. You could even use the two approaches together by retrieving the current date and time in UTC using the DateTimeOffset type:

var now = DateTimeOffset.UtcNow;

Wrapping up

Handling time is such an important task in programming, but it’s often done wrong because it is such a messy domain.

In this post, you’ve learned different ways to retrieve the current time in C#. The main takeaway is that using a DateTime with Kind set to Local is, more often than not, the wrong choice. You’re better off using a value whose Kind is set to Utc or even using DateTimeOffset.

For calculations, always use universal time. For instance:

DateTime start = DateTime.Now;

// lots of things happen

DateTime end = DateTime.Now;

var timeElapsed = end - start;

The code above might look innocent enough, but it hides a bug. If a daylight saving time transition happens between the initiation of the two variables, you’ll end up with a wrong value that has an extra hour or is missing one hour. For calculations like this, DateTime.UtcNow is the friend you need.

If you are frequently working with time-stamped data and need a storage solution, be sure to check out InfluxDB and the InfluxDB C# client library as well.

C# current time FAQs

We’ll now answer some common questions about dealing with the current time in C#.

Is it possible to display the current time in different time zones using C#?

Yes, of course. Let’s say that, for whatever reason, I need to display the current time using the Tokyo time zone. The first thing you need to do is to obtain the current time:

var now = DateTime.UtcNow;

Had I used DateTime.Now, things would work just the same. I used UtcNow, though, because we just discussed how it’s a best practice. The next step is to retrieve the target time zone:

TimeZoneInfo tokyoTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");

Finally, you perform the conversion:

var nowInTokyo = TimeZoneInfo.ConvertTime(now, tokyoTimeZone);

The result is a DateTime value set to the current time in Tokyo.

How can I format the current time output in C#?

Simply call ToString() on a DateTime or DateTimeOffset object, and you’ll get a formatted string according to the current culture of your machine. Here are some examples:

using System.Globalization;

Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); // displays 2/16/2024 10:58:38 PM

Console.WriteLine(DateTime.UtcNow.ToString());

Thread.CurrentThread.CurrentCulture = new CultureInfo("pt-BR"); // displays 16/02/2024 22:58:38

Console.WriteLine(DateTime.UtcNow.ToString());

Thread.CurrentThread.CurrentCulture = new CultureInfo("ja-JP"); // displays 2024/02/16 22:58:38

Console.WriteLine(DateTime.UtcNow.ToString());

Of course, there are other ways in which to display the date and time. For instance, you can use the default long string representation for both date and time. It also varies with culture, so I’m using the same three cultures from the previous example:

using System.Globalization;

Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

Console.WriteLine();

Console.WriteLine("English, United States");

Console.WriteLine(DateTime.UtcNow.ToLongDateString());

Console.WriteLine(DateTime.UtcNow.ToLongTimeString());

Console.WriteLine();

Console.WriteLine("Portuguese, Brazil");

Thread.CurrentThread.CurrentCulture = new CultureInfo("pt-BR");

Console.WriteLine(DateTime.UtcNow.ToLongDateString());

Console.WriteLine(DateTime.UtcNow.ToLongTimeString());

Console.WriteLine();

Console.WriteLine("Japanese, Japan");

Thread.CurrentThread.CurrentCulture = new CultureInfo("ja-JP");

Console.WriteLine(DateTime.UtcNow.ToLongDateString());

Console.WriteLine(DateTime.UtcNow.ToLongTimeString());

Here are the results:

English, United States

Friday, February 16, 2024

11:03:07 PM

Portuguese, Brazil

sexta-feira, 16 de fevereiro de 2024

23:03:07

Japanese, Japan

2024216日金曜日``

23:03:07

And, of course, you can use custom format strings, from which you have innumerable options.

What is the difference between Datetime.Now and today in C#?

Our final question: what’s the difference between DateTime.Now and DateTime.Today in C#? They both return a DateTime value. But the difference is that, by using DateTime.Today, the time portion is set to zero. So you’d use DateTime.Today in situations where you’re interested only in the date component, but not the time.

Since nowadays you have the DateOnly type for that use case, I wouldn’t use DateTime.Today.

This post was written by Carlos Schults. Carlos is a skilled software engineer and an accomplished technical writer for various clients. His passion is to get to the bottom (the original source) of things, and captivate readers with approachable and informative technical content.